Demo The code below highlight the words in the paragraph if it matches on the inputted keywords or text from the user. Gets the value from the text box Split if the words are separated by space Store the values in an array Pass those values in the function and use RegExp to evaluate If found, replaces the text with added span tag for the highlight. $.fn.wrapInTag = function (opts) { var words = opts.words || [], regex = RegExp(words.join('|'), 'gi'), replacement = '<span class="highlight">$&</span>'; return this.html(function () { return $(this).text().replace(regex, replacement); }); }; $('#terms').keyup(function () { var keywords = []; keywords = $(this).val().split(" "); $('p#text-body').wrapInTag({ words: keywords }); }); Demo
Comments
Post a Comment
Feel free to ask, suggest and comment regarding this post/blog. You can also contact me through e-mail, just always use the contact page. Thank you for visiting this blog.