How to use RegExp correctly
I am trying to replace '$$$' with a space using JavaScript. just like this.
I have the following code:
var splitSign = '$$$';
var string = 'hello$$$how$$$are$$$you';
var regex = new RegExp(splitSign,'g');
var res = string.replace(regex,' ');
console.info(res);
As a result, the string does not change! any ideas why?
source to share
You need to exit $
.. as this is a special character in regex (meaning of end of line)
var splitSign = '\\$\\$\\$'; (if creating new RegExp)
Otherwise, just use:
string.replace(/\$\$\$/g,' ');
code:
var splitSign = '\\$\\$\\$';
var string = 'hello$$$how$$$are$$$you';
var regex = new RegExp(splitSign,'g');
var res = string.replace(regex,' ');
alert(res);
source to share
$
- a special metacharacter in regular expressions. It indicates the end of the line, just as it ^
indicates the beginning.
To use these special characters, you must avoid them by preceding them with a backslash - this will cause the regex engine to literally use the character and not parse it as a special metacharacter. However, due to the fact that you are using the constructor RegExp
, you need to double the allocation of special metacharacters.
var splitSign = '\\$\\$\\$';
As mentioned in other answers, what you are trying to do is easily accomplished without regex. Simple enough here string.replace
. If you want to replace multiple instances, you can specify a flag g
to indicate global match.
Link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
source to share
as i explained ... string.replace without RegExp only changes the first occurrence of the string.
I found the following answer: How to replace all occurrences of a string in JavaScript?
it has exactly what I need.
first .. auto escaping string:
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
and then replace the function
function replaceAll(string, find, replace) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
source to share