0

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;'
  };
cedevita
  • 13
  • 1
  • 7
  • You can read this: [http://stackoverflow.com/questions/1229518/javascript-regex-replace-html-chars](http://stackoverflow.com/questions/1229518/javascript-regex-replace-html-chars). – caballerog Nov 29 '15 at 22:33

1 Answers1

2

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;
    }
Henrik Nielsen
  • 410
  • 2
  • 6