I want to replace this: "[ID]" with this "ad231-3213-e12211"
I was using this regular expression: /\[ID\]/i
And it was working perfectly with .replace(/\[ID\]/i, id)
Now I encapsulated it in this function:
self.changeUrl = function (url, id, replaceExp) {
replaceExp = replaceExp === 'undefined' ? new RegExp("\[ID\]") : replaceExp instanceof RegExp ? replaceExp : new RegExp("\[ID\]"); // basically ensure that this is a regexp
return url.replace(replaceExp, id);
};
and this:
self.changeUrl = function (url, id, replaceExp) {
replaceExp = replaceExp === 'undefined' ? new RegExp("\u005BID\u005D") : replaceExp instanceof RegExp ? replaceExp : new RegExp("\u005BID\u005D"); // basically ensure that this is a regexp
return url.replace(replaceExp, id);
};
And neither of them work, what is it that I am missing?
Since you are passing a string to your RegExp
constructor, you'd need to escape the \
character inside the string as well. Therefore, use \\[
which will actually become \[
inside the string variable; whereas \[
will become [
only.
new RegExp( "\\[ID\\]" )
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