RegExp JavaScript Bracket

I want to replace this: "[ID]" with this "ad231-3213-e12211"

I used this regex: /\[ID\]/i

And he worked great 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 none of them work, what am I missing?

+4
source share
3 answers

Since you are passing the string to your constructor RegExp, you also need to avoid the character \inside the string. So use \\[that will actually become \[inside the string variable; then how \[will it become [.

new RegExp( "\\[ID\\]" )
+4
source

To make sure:

, [ID], , :

self.changeUrl = function (url, id, replaceExp) {
   return (replaceExp instanceof RegExp) ? url.replace(replaceExp, id)
                                         : url.replace('[ID]', id);
};

self.changeUrl = function (url, id, replaceExp) {
   return (replaceExp === 'undefined') ? url.replace('[ID]', id)
                                       : url.replace(replaceExp, id);
};

( , )

+2

"\[ID\]"- this basically converts to regex as [ID], because the backslash in JavaScript is used as an escape character

+1
source

Source: https://habr.com/ru/post/1544999/


All Articles