<p>I need to highlight, case insensitively, given keywords in a JavaScript string.</p>

<p>For example:</p>

<ul>
<li><code>highlight("foobar Foo bar FOO", "foo")</code> should return <code>"&lt;b&gt;foo&lt;/b&gt;bar &lt;b&gt;Foo&lt;/b&gt; bar &lt;b&gt;FOO&lt;/b&gt;"</code></li>
</ul>

<p>I need the code to work for any keyword, and therefore using a hardcoded regular expression like <code>/foo/i</code> is not a sufficient solution.</p>

<p>What is the easiest way to do this?</p>

<p>(This an instance of a more general problem detailed in the title, but I feel that it's best to tackle with a concrete, useful example.)</p>

You
can
use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.
Here is such a function for javascript (
source
):
```
```
function preg_quote (str, delimiter) {
  //  discuss at: https://locutus.io/php/preg_quote/
  // original by: booeyOH
  // improved by: Ates Goral (https://magnetiq.com)
  // improved by: Kevin van Zonneveld (https://kvz.io)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  //   example 1: preg_quote("$40")
  //   returns 1: '\\$40'
  //   example 2: preg_quote("*RRRING* Hello?")
  //   returns 2: '\\*RRRING\\* Hello\\?'
  //   example 3: preg_quote("\\.+*?[^]$(){}=!<>|:")
  //   returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:'

  return (str + '')
    .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
}
```
```
So you could do the following:
```
```
function highlight(str, search) {
    return str.replace(new RegExp("(" + preg_quote(search) + ")", 'gi'), "<b>$1</b>");
}
```
```