Manu Singh
Manu Singh

Reputation: 414

Find alphanumeric characters, text and replace with HTML

I'm trying to find and replace text in an HTML. And adding a bold element around the text.

For example, lets say I have the following text:

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

If user searches for "test" in my HTML string, I need to show all text containing search text in bold.

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

This is working using the below code:

$.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']
});

But the above javascript approach fails if I search something like: *test or /test Regex doesn't support here. There are multiple approaches over net but none of them worked for alphanumeric text.

Upvotes: 0

Views: 131

Answers (2)

Ahs N
Ahs N

Reputation: 8366

This is how I would perform the text highlight:

$("#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

Upvotes: 2

Radek Pech
Radek Pech

Reputation: 3098

You need to escape the RegExp input. See How to escape regular expression in javascript?

function escapeRegExp(string){
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

Upvotes: 0

Related Questions