How to use Variable in a Regular Expression in JavaScript
In this tutorial, we are going to learn about using a variable in a regular expression (regex).
Consider we have a string
and we need to remove all yes
in that string.
We can do that by using a replace()
method.
Example:
const str = "Hello yes what are you yes doing yes"
// str.replace(regex-pattern,replacevalue)
const newstr = str.replace(/yes/g,'');
console.log(newstr);
//"Hello what are you doing "
In the above code, we have passed the regex
pattern as an argument to the replace()
method instead of that we can store the regex pattern in a variable
and pass it to the replace
method.
Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method (
new RegExp()
).
If we try to pass a variable to the regex literal pattern it won’t work.
const str = "Hello yes what are you yes doing yes"
const removeStr = "yes"
const regex = `/${removeStr}/g` // wrong way
const newstr = str.replace(regex,''); // won't work
The right way of doing it is by using a regular expression constructor new RegExp()
.
const str = "Hello yes what are you yes doing yes"
const removeStr = "yes" //variable
const regex = new RegExp(removeStr,'g'); // correct way
const newstr = str.replace(regex,''); // it works
In the above code, we have passed the removeStr
variable as an argument to the new RegExp()
constructor method.