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?
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
You can try:
"2**".replace(/[\+\-\*\/]+$/, "")
You can also try:
"2**".replace(/[-+*/]+$/, "");
Suggested by l'L'l. Or use negation:
"2**".replace(/[^0-9]+$/, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With