Description:

In this article, I will explain how to find, replace and highlight a word using Jquery.  

To find occurrence of string use match() method.

Syntax:

string.match(regularexpression)

match() used to search string with the regular expression and it will return only the first match in the string

If no match is found, it will return null value.

If the word matches with the target string, some action will happen based on your requirement.

To replace the string with new value use replace() method.

Syntax:

string.replace(searchvalue, targetstring)

replace() method used to searches string with the regular expression and it will return the new string where the string values are replaced.

To highlight a word, add style property with the target values.

The below example program will explain how to find, replace and highlight a word using Jquery.

Example Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var searchblock = ['p'];
            $("#TextBox1").bind('keyup', function (e) {
                var findtext = $("#TextBox1").val();
                $.each(searchblock, function (i) {
                    var Wholetexts = $('p').text();
                    Wholetexts = Wholetexts.replace(findtext, function (e) {
                        return "<span style='background-color: gray;'>" + e + "</span>";
                    });
                    $('p').html(Wholetexts);
                });
            });
            $("#btnReplace").click(function () {
                var find = $('#TextBox1').val();
                var replacewith = $('#TextBox2').val();
                $('p').html($('p').html().replace(find, replacewith));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            This is the sample text for find and replace example</p>
        <asp:Label ID="Label1" runat="server" Text="Find"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Replace With"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <input id="btnReplace" type="button" value="Replace" />
    </div>
    </form>
</body>
</html>

Highlight a word with jQuery, Highlighting search words with jQuery, Search & Highlight using JQuery, Find and Replace with JQuery, Highlight search terms, Use jQuery to find and replace multiple words on the page

2 comments:

 
Top