Reputation: 3823
what is wrong, as explained by an example:
form = 'some other [1][2] data ... data[Company][c_list][2][name_2] ... some other data';
form.replace(new RegExp('[c_list][2]', 'g'), '[c_list][1]');
get: data[Company][c_list][2][name[c_list][1]]
need: data[Company][c_list][1][name_2]
What is wrong with my code?
Thanks
Upvotes: 0
Views: 58
Reputation: 700262
The characters [
and ]
are used to make a set, so [c_list]
in the regular expression doesn't match the character sequence [c_list]
, it matches one character which is c
, _
, l
, i
, s
or t
.
Escape the characters [
and ]
in the expression. As you are writing the pattern as a string, you need to use \\
to put \
in the pattern:
form.replace(new RegExp('\\[c_list\\]\\[2\\]', 'g'), '[c_list][1]');
You can also write the regular expression as a literal, then you use just \
to escape characters:
form.replace(/\[c_list\]\[2\]/g, '[c_list][1]');
Upvotes: 3
Reputation: 5962
In a regular expression [...]
has a special meaning of defining a character class. I think you are looking for
form.replace(new RegExp('\[c_list\]\[2\]', 'g'), '[c_list][1]');
where the brackets have been escaped.
Upvotes: 1