3

I have an object, and inside my HTML I use tags of the form [itemkey] to refer to the value of the itemkey property of that object, and want to replace these tags with their values. My JavaScript code looks like this:

_.forEach(objectItem,function(val,key){
  var re = new RegExp('\[' + key +'\]','g');
  htmlDump = htmlDump.replace(re,val)
});

But it does not work. What is wrong?

8
  • 1
    You need to double escape the special characters in RegExp constructor. Use new RegExp('\\[' + key + '\\]'); Commented Dec 27, 2015 at 13:26
  • I tried It, but did not works again. Commented Dec 27, 2015 at 13:27
  • Does key contain any special characters? Commented Dec 27, 2015 at 13:28
  • Why not just new RegExp(key); Commented Dec 27, 2015 at 13:30
  • 1
    I guess, the issue is with the value of variable htmlDump being replaced in the next iteration. Commented Dec 27, 2015 at 13:37

1 Answer 1

4

Whatever manipulation of the HTML you do, nothing you do will have any effect until you replace the HTML of the document.

Other than that, there is no logical reason why @Tushar's approach as given in the first comment would not work (except that it needed a g flag):

new RegExp('\\[' + key + '\\]', 'g');

Overall, this approach is flawed. You are replacing the entire HTML; for instance, that will wipe out all event listeners. Instead, you should iterate through the DOM and apply your transformation to each text node.

Please be aware that ideally you should be escaping the key in order to avoid regexp-related characters in it from breaking the regexp.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.