I have the following code:
text = 'check this regex<placeholder>, it will do what you want';
result = text.replace('<placeholder>', ' `^sql$`');
console.log(result);
As you can see, the result is
check this regex `^sqlcheck this regex, it will do what you want
when i would expect it to be
check this regex `^sql$`, it will do what you want
Why is this happening? and... how can I fix it?
The function
replace
has an interesting behavior regarding the second parameter : (bolds are mine).Approximate translation:
The replacement string can include the following replacement patterns:
$$
insert a "$".$&
Inserts the substring that matches the search.$`
Inserts the portion of the string that precedes the substring that matches the search.$'
Inserts the portion of the string that follows the substring that matches the search.$n
Where n is a positive integer and less than 100, insert the nth sub-match in parentheses (capture group), assuming the pattern (first parameter) is a regular expression.That is, in this case it is added
^sql
and after this the entire string that precedes the match is added . It can be fixed by doubling the $ character: