最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - how to replace '[[' with '${' in javascript - Stack Overflow

programmeradmin1浏览0评论

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);

发布评论

评论列表(0)

  1. 暂无评论