Petru Lebada
Petru Lebada

Reputation: 1682

Replacing matched string with another

I'm trying to create a search box , to look for the searched pattern in html tags like p,span,etc,just like the ctrl+f option of the browser.

Javascript :

function searchKeyword(){
        var keyword = document.searchform.searchbox.value;
        $("#paragraph").each(function() {
            var string = $(this).text();
            newstring = string.replace(keyword, '<span style="background-color: #faf701;">'+keyword+'</span>');
            $(this).text(newstring);
        });
    }

The only issue is that,it doesn't read the string as a html markup,but as a simple string and it outputs exactly:

<span style="background-color: #faf701;">'+keyword+'</span>

Instead of a highlighted string.

Upvotes: 0

Views: 30

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

because you are using .text(), since you want to render the html content use .html()

$(this).html(newstring);

Since you have id selector, there is no need to use .each()

function searchKeyword() {
    var keyword = document.searchform.searchbox.value;

    $("#paragraph").html(function (i, html) {
        return $(this).text().replace(keyword, '<span style="background-color: #faf701;">' + keyword + '</span>');
    })
}

Use a regex to replace multiple matches

function searchKeyword() {
    var keyword = document.searchform.searchbox.value;
    var regex = new RegExp(RegExp.escape(keyword), 'g')

    $("#paragraph").html(function (i, html) {
        return $(this).text().replace(regex, '<span style="background-color: #faf701;">' + keyword + '</span>');
    })
}


if (!RegExp.escape) {
    RegExp.escape = function (value) {
        return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}

Upvotes: 1

Related Questions