How can I pass a variable into a JavaScript RegExp match method? I have this code: let rgx = new RegExp(/(?<= )(word1|word2|word3)(?= )/).source; Code (markup): What I'd like to do is store 'word1|word2|word3' in a variable, and then integrate it in the code above. I searched Google and tried in multiple ways, but nothing seems to work. As a quick example, the following code doesn't work... let regex_variable = "word1|word2|word3"; let rgx = new RegExp("/(?<= )(" + regex_variable + ")(?= )/").source; Code (markup): Thank you, Alex
).source; Do you see the problem here? You're pulling the string value of it, instead of the actual regexp object.
Yes, because I'm using this code format... let rgx1 = new RegExp(/(?<= )(word1|word2|word3)(?= )/).source; let rgx2 = new RegExp(/(additional regular expressions here)/).source; let rgx3 = new RegExp(/(additional regular expressions here)/).source; let final_regex = new RegExp(rgx1 + "|" + rgx2 + "|" + rgx3,'gi'); Code (markup): I only listed three regular expressions above, but I have around twenty, and this kind of approach enables me to keep everything organized and easy to follow. Right now I'm looking for a way to use variables inside the RegExp methods above. This would add flexibility and simplify things even more. What's the best way to do this, while keeping the format listed above? Sorry, my JS experience is very limited. I'm using this with a script that highlights keywords on web pages. Alex
I don't think you can "or" (|) between /exp/ in JS. Though I'm hoping this is server-side code... because if your client-side code is getting that convoluted with the regex, something is SERIOUSLY wrong with either the data, or how the server is handling it.