Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Bracket RegExp

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?

like image 615
Callum Linington Avatar asked Mar 19 '23 07:03

Callum Linington


1 Answers

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\\]" )
like image 121
hjpotter92 Avatar answered Mar 27 '23 22:03

hjpotter92