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 =>
No answers yet.
Log in to leave an answer
Blogs
Working with the File System in Swift: A Complete Guide
Generics in Go: why they are needed and how to use them for beginners
Best JavaScript Portfolio Projects: From Beginner to Pro
#pragma mark in Swift 2025: Code Organization Secrets They Don't Tell You About