1

I am trying to write a regex Replaces all 00 before and at the end of a string

"1203444" ---> Pass
"01212" ---> 1212
"12233434" ---> 12233434
"000000023234" ---> 23234
"34340000" -----> 3434
"00023300000" ----> 2333

Regex is kind of new to me.

"000123300".replace(/^0+/, "");   --> strips the first zeros

I tried numerous times to strip the last zeros to no avail. Any help would be appreciated.

Nuru Salihu
  • 4,526
  • 16
  • 61
  • 110
  • Does this answer your question? [Remove/ truncate leading zeros by javascript/jquery](https://stackoverflow.com/questions/8276451/remove-truncate-leading-zeros-by-javascript-jquery) – Fcmam5 Sep 21 '20 at 13:34
  • How about all the zeros? `"00000000000"` --------> ??? – Thân LƯƠNG Sep 21 '20 at 13:48
  • I found answer in this post. https://stackoverflow.com/questions/24295121/remove-leading-and-trailing-zeros-from-a-string – Thân LƯƠNG Sep 21 '20 at 13:50

1 Answers1

4

Here is the regex you are looking for:

'000123300'.replace(/^0+|0+$/g, '')

This will match one or many zeros (0+) in the start (^0+) or (|) in the end (0+$) of the given string, and replace all matches (//g) with empty strings.

VisioN
  • 138,460
  • 30
  • 271
  • 271
  • 1
    Did you mean `/g`? I don't understand why global is necessary - we are using `$`... - Please explain. Thank you! – iAmOren Sep 21 '20 at 13:43
  • 1
    @iAmOren. You could just try it. `'000123300'.replace(/^0+|0+$/, '') //=> "123300"`. Without the global flag, we would just replace the *first* occurrence found. – Scott Sauyet Sep 21 '20 at 14:10
  • Thank you. I did try it before asking you. Now I get it = you explained well ("just replace the first"). – iAmOren Sep 21 '20 at 14:15