I have a very simple regex that I am using for highlighting search terms in my application. If a user types in 'stack' into the search form, for example, the following regular expression is used as a string argument for preg_match_all
to highlight the results:
"/\b((stack|stacks))\b/i"
I am using json_encode
to output some of my configuration options for my application, including the regex above. I need this regex on the client-side because I am lazy-loading pagination items in an infinite-scroll fashion, and I want to take advantage of the client-side to parse the HTML for the proper search term highlighting.
My JS configuration object now appears similar to:
config = {
searchRegex: "/\b((stack|stacks))\b/i",
// ... more options
}
If searchRegex
wasn't a string, I wouldn't have a problem. It would automatically be a regular expression object, and there is nothing in that regex that JavaScript doesn't support. But now, I have to resort to parsing the string to get the appropriate arguments for the RegExp
constructor, which involves removing the delimiters and getting the modifier(s). With all the escaped characters that could be present, this doesn't seem like a viable or sane option.
How would I convert searchRegex
to become a regular expression object?