admin管理员组

文章数量:1434949

I tried to replace [[ with ${.

var str = "it is [[test example [[testing";
var res = str.replace(/[[[]/g, "${");

I am getting the result "it is ${${test example ${${testing" but I want the result "it is ${test example ${testing".

I tried to replace [[ with ${.

var str = "it is [[test example [[testing";
var res = str.replace(/[[[]/g, "${");

I am getting the result "it is ${${test example ${${testing" but I want the result "it is ${test example ${testing".

Share Improve this question edited Aug 26, 2015 at 11:23 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Aug 26, 2015 at 11:19 Akash RaoAkash Rao 9283 gold badges12 silver badges25 bronze badges 1
  • 1 Why the downvote? The question is ok, there's a clear explanation of the problem and a sample code of what's been tried.. – Ben Commented Aug 26, 2015 at 11:22
Add a ment  | 

4 Answers 4

Reset to default 5

Your regex is incorrect.

[[[]

will match one or two [ and replace one [ by ${.

See Demo of incorrect regular expression.

[ is special symbol in Regular Expression. So, to match literal [, you need to escape [ in regex by preceding it \. Without it [ is treated as character class.

var str = "it is [[test example [[testing";
var res = str.replace(/\[\[/g, "${");
//                     ^^^^

document.write(res);

you want to escape the [ using \

var res = str.replace(/\[\[/g, "${");

Just problem with escape characters. use \ before [.

var str = "it is [[test example [[testing";
var res = str.replace(/\[\[/g, "${");

If you don't want to use regex

var res = str.split('[[').join('${');

Sample Here:

var str = "it is [[test example [[testing";
var res = str.split('[[').join('${');

document.write(res);

本文标签: regexhow to replace 3939 with 3939 in javascriptStack Overflow