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
Replace All
Highlight All
That’s its !!!
.NET Professional | Microsoft Certified Professional | DZone’s Most Valuable Blogger | Web Developer | Author | Blogger
Doctorate in Computer Science and Engineering
Microsoft Certified Professional (MCP) with over 12+ years of software industry experience including development, implementation & deployment of applications in the .NET framework
Experienced and skilled Agile Developer with a strong record of excellent teamwork, successful coding & project management. Specialises in problem identification and proposal of alternative solutions. Provided knowledge and individual mentoring to team members as needed
Among top 3% overall in terms of contribution on Stack Overflow (~2.3 million people reached my posts). Part of the top 1% Stack Overflow answerers in ASP.NET technology.
DZone’s Most Valuable Blogger (MVB)
Created and actively maintain the TechCartNow.com tech blog while also editing, writing, and researching topics for publication.
Excellent skills in Application Development using C#/Vb.Net, .NET Framework, ASP.NET, MVC, ADO.NET, WCF, WPF, Web API, SQL Server, jQuery, Angular, React, BackboneJS