javascript正则表达式多重条件

时间:2016-04-25 16:38:08

标签: javascript regex

我有一个html实体替代&看起来像这样:

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

工作正常,不会替换&但会替换&

如何为我的函数的正则表达式添加多个条件,以便它不会混淆其他html实体,如:

'
"
>
<

我测试:

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

console.log(htmlEntities(xxx));

它会将&lt;替换为&amp;lt;而这不是我想要的,我需要让&lt;无法像示例&aaa&amp;一样成为&amp;aaa&amp; {{1}}

希望你明白我的意思,任何想法?

1 个答案:

答案 0 :(得分:1)

您可以在正则表达式中使用|来制作替代方案。

&#13;
&#13;
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;');
}
&#13;
&#13;
&#13;