I need to make a replace of a plus sign in a javascript string. there might be multiple occurrence of the plus sign so I did this up until now:
myString= myString.replace(/+/g, "");#
This is however breaking up my javascript and causing glitches. How do you escape a '+' sign in a regular expression?
Use the replace() method to return a new string with a substring replaced by a new one. Use a regular expression with the global flag ( g ) to replace all occurrences of a substring with a new one.
Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.
myString = myString.replace(/\+/g, "");
You need to escape the +
as its a meta char as follows:
myString= myString.replace(/\+/g, "");
Once escaped, +
will be treated literally and not as a meta char.
I prefer this:
myString.replace(/[+]/g, '').
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