I want to search words in a string, let’s say I input the word “test”, and it will return all results matching “test”, but I don’t know how to pass word I inputed to regex constructor. For example that shown below, if I directly enter /btestb/g
in matchAll
, then it all good, but what if I want to search different words, so I try /b${word}b/g
, but doesn’t work.
Do you know any solution that I can use? Thanks in advance.
const word = "test";
const regex = `/b${word}b/g`;
const str = 'test1 test 2';
const array1 = [...str.matchAll(new RegExp(regex, "g"))];
const array2 = [...str.matchAll(new RegExp(/btestb/g, "g"))];
console.log(array1);
// expected output: Array ["test"] // however it return empty array []
console.log(array2);
// expected output: Array ["test"] // it do return expected result