Reputation: 18118
Hi all ia m trying to replace all characters of "+" in a string by using the code below:
var findValue = "+";
var re = new RegExp(findValue, 'g');
searchValueParam = searchValueParam.replace(re, " ");
However i recieve this exception:
SyntaxError: Invalid regular expression: nothing to repeat
previously i applied just searchValueParam = searchValueParam.replace("+", " "); but that only replaces the first occurrence, not all.
Any suggestions?
Upvotes: 0
Views: 130
Reputation: 4737
If you want to keep the code you have, replace
var findValue = '+';
with
var findValue = '\\+';
Plus has a special meaning (quantifier) in a regular expression. This is why we need to escape it with a backslash: \+. However, when you place this in a string, the backslash itself has to be escaped as it has a special meaning in a string. This is how we end up with '\\+'.
In conclusion, this
var re = new RegExp('\\+', 'g')
is equivalent to this
var re = /\+/g;
Upvotes: 1
Reputation: 10838
For multiple replacements you need to use regex with the global (g
) modifier, however +
has a special meaning (the previous item 1 or more times), so it needs to be escaped.
searchValueParam = searchValueParam.replace(/\+/g,' ');
Upvotes: 3
Reputation: 74146
You need to escape the +
sign:
searchValueParam.replace(/\+/g, " ");
Upvotes: 2