Karolina Ticha Karolina Ticha - 3 months ago 9
HTML Question

jQuery if input value matches character in div

Here is my html

<input type="text" />
<div>
<p>Apple</p>
<p>Peach</p>
<p>Bannana</p>
<p>Tomato</p>
</div>


And my jQuery code yet

var items = $("div").find("p").text();

console.log(items);


How can I highlight each character inside div p that matches value in input? Let's say that users write down in input character "a". Page should look like this, even A character in apple should be bold.

Apple

Peach

Bannana

Tomato

here is codepen as well

Answer

One option is:

// Borrowed from:
// http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript#answer-3561711
function escapeRegex(str) {
   return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var items = $("div").find("p");

$('input').on('keyup', function() {
   var reg = new RegExp('(' + escapeRegex(this.value) + ')', 'gi');
   items.html(function() {
      return this.textContent.replace(reg, "<b>$1</b>");
   });
});

https://jsfiddle.net/xbqetxdo/