-3

i want to replace all [$dummyTest$] with other text eg. realtext

Lorem ipsum dolor sit amet [$dummyTest$], consectetur adipiscing elit. Proin vel augue laoreet, consectetur felis a [$dummyTest$], laoreet sem. Ut quis sapien tincidunt, consectetur diam aliquam, ultrices nisi [$dummyTest$]. Ut bibendum augue odio, eget imperdiet sapien maximus at.

Output : Lorem ipsum dolor sit amet realText, consectetur adipiscing elit. Proin vel augue laoreet, consectetur felis a realText, laoreet sem. Ut quis sapien tincidunt, consectetur diam aliquam, ultrices nisi realText. Ut bibendum augue odio, eget imperdiet sapien maximus at.

Jitender Bisht
  • 125
  • 1
  • 2
  • 13
  • What is your use case? Have you considered using a template engine instead? – Nico Van Belle May 18 '17 at 10:31
  • it's client request i am using this keyword [$identity$] as identity, so that i can replace this keyword with real data. example [$Name$] = "Some Name", [$Address$] = "Some Address" ets – Jitender Bisht May 18 '17 at 10:39

2 Answers2

1

You could do this:

var str = oldStr.replace(/\[\$\w*\$\]/g, id);

Which will replace all occurences of [$someVarible$] with whatever string is in id.

If you want to replace a specific variable you could do:

 var str = oldStr.replace(/\[\$myVar\$\]/g, myVar);

So in your specific example.

var orgString = "Lorem ipsum dolor sit amet [$dummyTest$], consectetur adipiscing elit. Proin vel augue laoreet, consectetur felis a [$dummyTest$], laoreet sem. Ut quis sapien tincidunt, consectetur diam aliquam, ultrices nisi [$dummyTest$]. Ut bibendum augue odio, eget imperdiet sapien maximus at."

var editedString = orgString.replace(/\[\$dummyTest\$\]/g, 'realText');

console.log(editedString);
Ozgar
  • 305
  • 2
  • 14
  • i have different different keyword. every key having some data and want to replace each keyword with data – Jitender Bisht May 18 '17 at 10:46
  • Updated my answer with what you need to do for that if you want to use regular expressions. Another way to go is http://stackoverflow.com/a/1408373/5897779 :) Here they define a function that builds the regex needed for replacing substrings in quite a neat fasion. – Ozgar May 18 '17 at 10:50
1

You can pass callback to String#replace method

var before = "Lorem ipsum dolor sit amet [$dummyTest$], consectetur adipiscing elit. Proin vel augue laoreet, consectetur felis a [$name$], laoreet sem. Ut quis sapien tincidunt, consectetur diam aliquam, ultrices nisi [$dummyTest$]. Ut bibendum augue odio, eget imperdiet sapien maximus at."

var texts = {
"[$dummyTest$]": "TEST",
"[$name$]": "SOME NAME"
}

var after = before.replace(/\[\$\w*\$\]/g, function(str){return texts[str]});

console.log(after);
barbsan
  • 3,418
  • 11
  • 21
  • 28