假设我有一个段落,我必须找到两个关键词,如'chemist's shop'和shop。
<div id="content"> <p>I have a shop which is known as chemist's shop and I need some medicine for my shop.</p> </div>
在上面的段落中 Chemist's shop 将替换为药房 商店将替换为商店
以下是我的代码。
var list= ["chemist's shop","shop"];
var text= $('#content').html();
var i, len = list.length, reg;
for (i = 0; i < len; i++) {
reg = new RegExp("\\b" + list[i] + "\\b", 'gi');
if (reg.test(text)) {
text = text.replace(reg, "<a href='#' style='color:red'>"+list[i]+"</a>");
}
}
}
我希望结果为
<div id="content"><p>I have a <a href='#' style='color:red'>store</a> which is known as <a href='#' style='color:red'>pharmacy</a> and I need some medicine for my <a href='#' style='color:red'>store</a>.</p></div>
当我首先运行代码时,化学家的商店被确定,然后商店部分被商店取代。
我试图获得输出但未能获得实际结果。 请帮我解决我的问题。非常感谢。
提前致谢。
答案 0 :(得分:0)
您需要创建一个包含要更新内容的新数组,然后在text.replace
中使用新数组的项目。
最后,您必须使用jQuery方法div#content
.html()
我已更新您的代码。检查工作代码段。
var list= ["chemist's shop","shop"];
var list2 = ["pharmacy", "store"];
var text= $('#content').html();
var i, len = list.length, reg;
for (i = 0; i < len; i++) {
reg = new RegExp("\\b" + list[i] + "\\b", 'gi');
if (reg.test(text)) {
text = text.replace(reg, "<a href='#' style='color:red'>"+list2[i]+"</a>");
}
$('#content').html(text);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"> <p>I have a shop which is known as chemist's shop and I need some medicine for my shop.</p> </div>
&#13;