将HTML中所需单词的第一次出现替换为另一个单词

时间:2019-03-27 13:28:58

标签: javascript html regex replace word

假设我的HTML字符串是:

<p>Example: This is my example string. This is one more Example sentence.</p>

我想用想要的单词替换第一次出现的单词,在这种情况下,将单词example用相同的单词替换成strong标签,使最终的字符串变为:

<p><strong>Example:</strong> This is my example string. This is one more Example sentence.</p>

所以当它渲染时,它变成:

**Example:** This is my example string. This is one more Example sentence.

1 个答案:

答案 0 :(得分:3)

您可以按照以下方式尝试使用replace()

var el = document.querySelector('p');
var word = 'Example:'
var output = el.textContent.replace(word, '<strong>'+word+'</strong>');
el.innerHTML = output;
<p>Example: This is my example string. This is one more Example sentence.</p>

您还可以尝试使用 非标准 $n with String.replace的RegEx:

var el = document.querySelector('p');
var output = el.textContent.replace(/(Example:)/, '<strong>$1</strong>');
el.innerHTML = output;
<p>Example: This is my example string. This is one more Example sentence.</p>