I need to highlight, case insensitively, given keywords in a JavaScript string.
For example:
highlight('foobar Foo bar FOO', 'foo')should return'<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>'
I need the code to work for any keyword, and therefore using a hardcoded regular expression like /foo/i is not a sufficient solution.
What is the easiest way to do this?
(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.)
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):
So you could do the following: