Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Remove last with global modifier not working

I have a regex like this:

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

And even though if it has the global modifier this won't work:

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

How do you fix this?


2 Answers

You need to use a quantifier with your character class. The + quantifier means "one or more" times. Also you can avoid escaping certain characters inside of 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
like image 197
hwnd Avatar answered Aug 04 '26 09:08

hwnd


You can try:

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

You can also try:

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

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

"2**".replace(/[^0-9]+$/, "");
like image 41
Georgi Naumov Avatar answered Aug 04 '26 08:08

Georgi Naumov