Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace '[[' with '${' in javascript

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".

like image 424
Akash Rao Avatar asked Aug 26 '15 11:08

Akash Rao


2 Answers

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);
like image 170
Tushar Avatar answered Oct 18 '22 17:10

Tushar


you want to escape the [ using \

var res = str.replace(/\[\[/g, "${");
like image 4
Jaromanda X Avatar answered Oct 18 '22 18:10

Jaromanda X