2015-09-02 157 views
0

我试图查找并替换HTML中的文本。并在文本周围添加一个大胆的元素。查找字母数字字符,文本并替换为HTML

例如,可以说我有以下文字:

<div>This is a test content and I'm trying to write testimonial of an user.</div> 

如果用户搜索我的HTML字符串“测试”,我需要显示粗体所有包含有文本搜索文本。

<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方法上面的失败: *测试或/测试 正则表达式不支持这里的。 网络上有多种方法,但它们都不适用于字母数字文本。

回答

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>")); 
}); 

Here is the JSFiddle demo

+0

仍然没有像 “*测试” 搜索字符串工作https://jsfiddle.net/ frzv0dnL/1/ –

+0

@RadekPech更新了符合urs的代码,它现在可以工作:) –

+0

@Ahs N:这就是我想要的。但它不适用于“* Test *”。理想情况下,它也应该采用Caps字符。 –