0

I'm trying to implement a search where I only match and bold the start of the word in Javascript.

So, if you search for "choc", "chocolate" would appear, but if you search for "late", Chocolate wouldn't appear.

I've got:

if( queryString.match(new RegExp('/\b'+inputField.val()+'/', 'gi')) )

And then to highlight the word:

var tempName = queryString.replace(new RegExp('(^|\b)(' + inputField.val() + ')(|$)','ig'), '$1<strong>$2</strong>$3');

But nothing is working the way I had hoped. Any ideas?

user3508995
  • 187
  • 1
  • 1
  • 13

1 Answers1

1

Example match:

Demo or Demo

RegExp:

/(^|\s)(late)/gmi

or

/\b(late)/gmi

This will match:

Chocolate latechoco

Example replacement:

var search = "Chocolate latechoco";
document.write(search.replace(/\b(late)/gmi, "<strong>$1</strong>"));

Also note that your search string inputField.val() should always be escaped. See this answer to learn how.

Community
  • 1
  • 1
dude
  • 5,678
  • 11
  • 54
  • 81