假设我的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.
答案 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>