"2" And even if ...">

Javascript - remove last one with global modifier not working

I have a regex:

("2*").replace(/[\+\-\*\/]$/g, "") -> "2"

      

And even if it has a global modifier, it won't work:

("2**").replace(/[\+\-\*\/]$/g, "") -> "2*"

      

How do you fix this?

+3


source to share


2 answers


You need to use quantifier with your character class. Ratio +

means "one or more" times. Also you can avoid escaping certain characters inside your class and remove the global modifier.

'2*****'.replace(/[-+*/]+$/, '') //=> "2"

      



Explanation:

[-+*/]+  # any character of: '-', '+', '*', '/' (1 or more times)
      $  # before an optional \n, and the end of the string

      

+6


source


You may try:

"2**".replace(/[\+\-\*\/]+$/, "")

      

You can also try:



"2**".replace(/[-+*/]+$/, "");

      

Offered by l'L'l. Or use negation:

"2**".replace(/[^0-9]+$/, "");

      

+4


source







All Articles