Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a plus sign in JavaScript?

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?

like image 919
William Calleja Avatar asked Mar 18 '10 10:03

William Calleja


People also ask

How do you replace something in JavaScript?

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.

How do you replace letters in JavaScript?

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.

What is replace (/ g in JavaScript?

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.


3 Answers

myString = myString.replace(/\+/g, "");
like image 176
Darin Dimitrov Avatar answered Oct 18 '22 06:10

Darin Dimitrov


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.

like image 10
codaddict Avatar answered Oct 18 '22 08:10

codaddict


I prefer this:

myString.replace(/[+]/g, '').
like image 5
David Avatar answered Oct 18 '22 07:10

David