JavaScript: Replace/Highlight All occurrence of a string or array of strings

Recently, one of my colleague was working on a task in which he need to take space separated string as input from the user, then split the string with space & highlight all occurrences of resulted array of strings on the page. In this article, I will explain one of the approaches of achieving the same.

Replace All

Here:

searchvalues is array of strings which need to be replaced in initialString with newvalue (replacement string).

var Common = {
    
    repaceAll: function (initialString, searchvalues, newvalue) {
        var values = searchvalues.join("|");
        if ($.trim(values) != '') {
            return initialString.replace(new RegExp(values, 'gi'), function () {
                return newvalue;
            });
        }
    }

};

Highlight All

Here:

searchvalues is array of strings which need to be highlighted in initialString.

var Common = {
    
    highlightAll: function (initialString, searchvalues) {
        var values = searchvalues.join("|");
        if ($.trim(values) != '') {
            return initialString.replace(new RegExp(values, 'gi'), function (x) {
                return "<mark>" + x + "</mark>";
            });
        }
    }
};

Full Working Sample Code

Sample HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div style="margin:50px">
        <input type="radio" name="select" value="highlight" checked="checked"> Highlight<br>
        <input type="radio" name="select" value="repace"> Replace<br>
        <input id="searchText" type="text" value="" placeholder="Space seperated text (for highlighting/repacement)" />
        <input id="replacement" style="display:none;" type="text" placeholder="Replacement text" />
        <button id="highlight">Highlight</button>
        <button id="replace" style="display:none;">Replace</button>
        <button id="reset" onclick="window.location.reload();">Reset</button>

        <div id="content" style="text-align:center;font-style:italic; font-size:xx-large; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif">
            Five red apples in a grocery store<br />
            Bobby bought one & then there were 4<br />
            Four red apples on an apple tree<br />
            Susie ate one & then there were 3<br />
            Three red apples. What did Alice do?<br />
            Why she ate one & then there were 2<br />
            Two red apples ripening in the sun<br />
            Tommy ate one, & now there was one<br />
            One red apple & now we are done<br />
            I ate the last one & now there are none!<br />
        </div>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script src="Scripts/replaceAll/replaceall.js"></script>
    </div>
</body>
</html>

Sample JavaScript Code

var Common = {
    init: function () {
        $(document).on("change", 'input[type="radio"]', Common.setView);
        $(document).on("click", "#replace", Common.replaceExample);
        $(document).on("click", "#highlight", Common.highlightExample);
    },

    setView: function () {
        if ($(this).val() == 'highlight') {
            $("#highlight").show();
            $("#replace").hide();
            $("#replacement").hide();
        }
        else {
            $("#highlight").hide();
            $("#replace").show();
            $("#replacement").show();
        }
    },

    replaceExample: function () {
        $("#replace").hide();
        var newvalue = $("#replacement").val();
        var searchvalues = $("#searchText").val().split(" ");
        var initialString = $("#content").html();
        var response = Common.repaceAll(initialString, searchvalues, newvalue);
        $("#content").html(response);
    },

    highlightExample: function () {
        $("#highlight").hide();
        var searchvalues = $.trim($("#searchText").val()).split(" ");
        var initialString = $("#content").html();
        var response = Common.highlightAll(initialString, searchvalues);
        $("#content").html(response);
    },

    repaceAll: function (initialString, searchvalues, newvalue) {
        var values = searchvalues.join("|");
        if ($.trim(values) != '') {
            return initialString.replace(new RegExp(values, 'gi'), function () {
                return newvalue;
            });
        }
    },

    highlightAll: function (initialString, searchvalues) {
        var values = searchvalues.join("|");
        if ($.trim(values) != '') {
            return initialString.replace(new RegExp(values, 'gi'), function (x) {
                return "<mark>" + x + "</mark>";
            });
        }
    }
};

$(function () {
    Common.init();
});

 

Output

Initial Screen

Initial Screen

Replace All

JavaScript replace All

Highlight All

JavaScript Highlight All

That’s its !!!

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *