我想用<mark> word </mark>替换所有出现的“单词”

时间:2019-12-05 05:00:44

标签: javascript regex replace

我想用包围单词的标记标签替换所有出现的单词。

这是我的输入字符串

var temp='<div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" >
  Child protection
</div>';

我的预期输出是

var temp='<div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" >
  <mark>Child</mark> protection
</div>';

但是我得到的输出是

var temp='<div title="Minimum Standards for <mark>Child</mark> Protection in Humanitarian Action (CPMS) | content of" >
  <mark>Child</mark> protection
</div>';

它将替换“标题”属性中的“孩子”一词。但是我想避免在title属性内进行替换。我该怎么做?

这是我目前的代码

var searchText="child";
var re = new RegExp(searchText, 'gi');
let htmlDataString = String(temp).replace(re, "<mark>$&</mark>");

2 个答案:

答案 0 :(得分:1)

使用DOMParser()

var temp = '<div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" >Child protection</div><div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" >Child protection</div>';

let domparser = new DOMParser()
let doc = domparser.parseFromString(temp, "text/html")

let searchText = "child";
let re = new RegExp(searchText, 'gi');

doc.body.querySelectorAll('[title]').forEach(el => {
  el.innerHTML = el.textContent.replace(re, "<mark>$&</mark>");
})

document.write(doc.body.innerHTML)
console.log(doc.body.innerHTML)

答案 1 :(得分:1)

以下代码可能对您有帮助

var temp= '<div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" > Child protection </div>';
var found = $(temp).filter("div").html();
var text = $(temp).filter("div").html().replace('Child','<mark>Child</mark>');
let htmlDataString = String(temp).replace(found, text);

以上代码的输出

<div title="Minimum Standards for Child Protection in Humanitarian Action (CPMS) | content of" > <mark>Child</mark> protection </div>