Avatar ·

How to use a variable in a regular expression in JavaScript?

Hi everyone! I'm new to JavaScript and trying to write a simple search function. I have an array of strings, and I want to find all elements that contain a specific word. The search word is passed as a function argument.\n\nThe problem is that I can't figure out how to insert a variable inside a regular expression. When I write like this:\n\n```javascript\nfunction searchItems(array, searchTerm) {\n const regex = /searchTerm/gi;\n return array.filter(item => regex.test(item));\n}\n```\n\n...it searches for the literal string "searchTerm", not the variable value. I tried using `new RegExp()`, but I still can't get it to work. Here's my current code:\n\n```javascript\nfunction searchItems(array, searchTerm) {\n const regex = new RegExp(searchTerm, 'gi');\n return array.filter(item =>