2

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,756
  • 17
  • 65
  • 116

1 Answers1

7

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
  • 143,310
  • 32
  • 282
  • 281
  • 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
  • 2
    @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