如何使用nodejs在字符串中查找字符实体



后有一个字符串

<!--
document.write("<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;'>&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a>");
//-->

如何在标签中获取htmlentities

&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;

如果您想获得每个html实体:

const rgx = /&#d+;/g;
const string = "<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;'>&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a>";

while ((match = rgx.exec(string)) !== null) console.log(match[0]);

如果你想把它们都放在一起:

const rgx = /(&#d+;)+/;
const string = "<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;'>&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a>";

console.log(rgx.exec(string)[0]);

这种RegEx的优点是可以处理包含HTMLEntities的每个字符串,而不考虑周围环境。

const html = "<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;'>&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a>";
const match = /<a[^>]+>([^<]+)</a>/.exec(html);
console.log('match: ', match[1]);
console.log('is-correct: ', match[1] === '&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;');


这是有效的,但我不明白为什么在标记中会有那么多实体编码。

只需使用split("")即可实现。我认为这是一个更好的解决方案,因为它不在乎href内部有什么,所以它可以是任何字符串,它会将其拆分。

const a = `document.write("<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;'>&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;&#52;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a>");`
const array = a.split("mailto:")[1].split("</a>");")[0]
console.log(array)

试试这个正则表达式:

const matches = str.match(/&#d+;/);

最新更新