我正在尝试在HTML中查找和替换文本。并在文本周围添加一个粗体元素。
例如,假设我有以下文字:
<div>This is a test content and I'm trying to write testimonial of an user.</div>
如果用户在我的HTML字符串中搜索“test”,我需要以粗体显示包含搜索文本的所有文本。
<div>This is a <b>test</b> content and I'm trying to write <b>test</b>imonial of an user.</div>
使用以下代码:
$.fn.wrapInTag = function(opts) {
var o = $.extend({
words: [],
tag: '<strong>'
}, opts);
return this.each(function() {
var html = $(this).html();
for (var i = 0, len = o.words.length; i < len; i++) {
var re = new RegExp(o.words[i], "gi");
html = html.replace(re, o.tag + '$&' + o.tag.replace('<', '</'));
}
$(this).html(html);
});
$('div').wrapInTag({
tag: 'b',
words: ['test']
});
但是,如果我搜索以下内容,上述javascript方法将失败: *测试或/测试 正则表达式不支持此处。 网上有多种方法,但没有一种方法适用于字母数字文本。
答案 0 :(得分:2)
这是我执行文字突出显示的方式:
$("#search").keyup(function(){
$("#text").html($("#text").html().replace("<b>", "").replace("</b>", ""));
var reg = new RegExp($(this).val().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),"g");
$("#text").html($("#text").text().replace(reg, "<b>"+$("#search").val()+"</b>"));
});
答案 1 :(得分:0)
您需要转义RegExp输入。见How to escape regular expression in javascript?
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}