0

I have a html entities replacement for & that look like this:

function htmlEntities(str) {
return String(str).replace(/&(?!amp;)/g, '&');
}

which are working fine that not to replace the & but will replace &

how do I add multiple condition to regex of my function so that it will not mess with other html entities like:

'
"
>
<

i test with:

var xxx = "1234 &aaa&amp; aaadas 'xxx' \" kkk <aasd> xxxxxxxxxxxxxxxx &lt;";

console.log(htmlEntities(xxx));

it will replace the &lt; to become &amp;lt; and this is not what I want, i need it to leave the &lt; untouch just like the example &aaa&amp; to become &amp;aaa&amp;

hope you get what I mean, any idea?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Teddybugs
  • 1,232
  • 1
  • 12
  • 37
  • 1
    There are better alternatives than a RegEx (Ask the DOM) E.g. http://stackoverflow.com/questions/7394748/whats-the-right-way-to-decode-a-string-that-has-special-html-entities-in-it / http://stackoverflow.com/questions/5796718/html-entity-decode – Alex K. Apr 25 '16 at 16:40
  • Why reinvent the wheel? – NullUserException Apr 25 '16 at 16:48

1 Answers1

1

You can use | in a regexp to make alternatives.

var xxx = "1234 &aaa&amp; aaadas 'xxx' \" kkk <aasd> xxxxxxxxxxxxxxxx &lt;";
console.log(htmlEntities(xxx));

function htmlEntities(str) {
  return String(str).replace(/&(?!(?:amp|apos|gt|lt);)/g, '&amp;');
}
Barmar
  • 741,623
  • 53
  • 500
  • 612