0

I've a string like this

var str = "<div class=\"@@obj.classname@@\" style="\@@obj.color@@\">@@obj.content@@</div>";

I'd like to create a function to dynamically change it and get this result

var result = "<div class=\"" + opt.obj.classname + "\" style="\" opt.obj.color + "\">" + opt.obj.content + "</div>";

Is it possibile to do it? How could I do that? the replace function might help? Thank you

Paolo Rossi
  • 2,490
  • 9
  • 43
  • 70
  • Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Armfoot Oct 12 '15 at 11:21
  • 1
    It's not a duplicate, because this requires the result not as a string but as executed javascript (requiring eval) – Chris Lear Oct 12 '15 at 11:26

2 Answers2

2

You can use eval to execute some code in a string. Before that, you need to make sure your string is proper code, so you would need to replace the @@parameter@@ with the parameter wrapped with ' and +. Something like this:

var str = "'" + str.replace(/@@(.*?)@@/g, "' + opt.$1 + '") + "'";
var result = eval(str);

Working example: https://jsfiddle.net/hj3grh1o/

Ángela
  • 1,405
  • 18
  • 24
1

Maybe try

eval "var result = " + str.replace(/@@(.*?)@@/g, '" + opt.$1 + "');
Chris Lear
  • 6,592
  • 1
  • 18
  • 26