In this small blog, I will show you how can we highlight the search pattern for the length paragraph. I have seen a lot of people manually writting their own logic to highlight the text. But here I will show you using regular expression.
Copy the below html
- <input type="text" id="search" placeholder="EnterSearch Text" /><br/>
- <div id="txtdesc" rows="40" cols="40" style="border:1px solid black">
- Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
- when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
- typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
- desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
- </div>
- <br/>
- <button id="btn">Search</button>
In the above code, I have taken a textbox to enter the search pattern. This pattern will be searched from the div section. A button, on click of which the entered pattern should be higlighted.
Now copy the below JavaScript.
- <script type="text/javascript">
-
- $('#btn').bind('click', function (e) {
- e.preventDefault();
- var searchTxtBox = $('#search');
- searchTxtBox.val(searchTxtBox.val().replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*"));
- var textarea = $('#txtdesc');
- var enew = '';
- if (searchTxtBox.val() != '') {
-
- enew = textarea.html().replace(/(<mark>|<\/mark>)/igm, "");
- textarea.html(enew);
-
- var query = new RegExp("("+searchTxtBox.val()+")", "gim");
- newtext= textarea.html().replace(query, "<mark>$1</mark>");
- newtext= newtext.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"</mark><mark>");
-
- textarea.html(newtext);
-
- }
- else {
- enew = textarea.html().replace(/(<mark>|<\/mark>)/igm, "");
- textarea.html(enew);
- }
- });
- </script>
In the above JavaScript, I have implemented the button click event. Actually what is done here is the entered text pattern is searched and replaced with <mark/> tag. <mark/> tag is a html 5 element used to highlight the text. Thats it.
Output:
The above used regular expression will search the pattern not only in the word but also as a partial text irrespective of case(either upper or lower case). In the below code, if the second parameter to Regex() class is passed as "im" only then, only the first occurance of search pattern is checked & hightlighted
- var query = new RegExp("("+searchTxtBox.val()+")", "im");
Conclusion
Hope this small code snippet will help you for achieving highlighting text using jQuery.