2015-09-02 155 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字符。 –