Sometimes, we want to use variable in string match with JavaScript.
In this article, we’ll look at how to use variable in string match with JavaScript.
How to use variable in string match with JavaScript?
To use variable in string match with JavaScript, we can use the RegExp
constructor to create our regex.
For instance, we write
const word = "Web Development Tutorial";
const vowels = "[aeiou]";
const re = new RegExp(vowels, "gi");
const arr = word.match(re);
to create a regex that match vowels with
const re = new RegExp(vowels, "gi");
The first argument is the regex pattern string and the 2nd argument is the string with the flags.
g
means we return all matches and i
means we search in a case-insensitive manner.
Then we call word.match
with re
to return an array of matches.
Conclusion
To use variable in string match with JavaScript, we can use the RegExp
constructor to create our regex.