Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

I wrote following code:

function convert(string) {
  var before = '&';
  var after= '&'; 
  var pattern = new RegExp(before, 'g');
  return string.replace(pattern,after);
}
convert("Dolce & Gabbana");

And it works just fine - returns Dolce & Gabbana. How could I do this through some loop, for multiple patterns, like this:

var multiple = {
    '&' : '&',
    '<' : '&lt;',
    '>' : '&gt;',
    '"' : '&quot;',
    '`' : '&apos;'
  };
share|improve this question

marked as duplicate by nhahtdh regex yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
You can read this: [stackoverflow.com/questions/1229518/…. – caballerog 2 days ago

1 Answer 1

up vote 0 down vote accepted

You could iterate over your multiple-object, like so:

    function convert(string) {
       var multiple = {
        '&' : '&amp;',
        '<' : '&lt;',
        '>' : '&gt;',
        '"' : '&quot;',
        '`' : '&apos;'
      };
      for(var char in multiple) {
        var before = char;
        var after= multiple[char]; 
        var pattern = new RegExp(before, 'g');
        string = string.replace(pattern,after);    
      }
      return string;
    }
share|improve this answer
    
Exactly what I was looking for! Thanks a lot! – cedevita 2 days ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.