【发布时间】:2020-12-17 13:08:24
【问题描述】:
我在执行以下任务时遇到问题:
我需要通过将它包含的一些单词链接到“阅读更多”页面来丰富包含 html 的字符串。不幸的是,当我要替换的搜索词开始重叠时,它变得很棘手。 我要么以嵌套链接结束,要么像下面的示例中那样,更长的术语不会被替换。
let html = `<p>So there is this Text in HTML containing words.</p>
<p>I want to link some special words to their read more pages.</p>
<p>But if search terms contain each other they re not linked correctly. Like the ones above.</p>`;
const linkTo = [
{term: 'words', link: 'https://example.com/words'},
{term: 'special words', link: 'https://example.com/special_words'},
];
for(const pair of linkTo){
const re = new RegExp(pair.term, "g");
html = html.replace(re, `<a href="${pair.link}">${pair.term}</a>`);
}
document.body.innerHTML = html;
<html><body></body></html>
在上面的例子中,第 2 行的“特殊词”应该链接到它自己的页面。
有什么想法吗?
提前致谢!
【问题讨论】:
-
您的问题需要澄清。 (对我来说)很难破译你想要完成的事情。
-
@GetSet 其实很清楚。
-
@WiktorStribiżew 我迷路了
标签: javascript html regex