Using variable name as Regex

I want to return missing value from a string by comparing it to another string with regex match method. Here is the code

let str = "abce";
let newStr = "abcde";
let str1 = newStr.match(/[^abce]/);
console.log(str1[0]);

It returns “d”. ( expected value)
But when I use variable name as regex -

let str = "abce";
let newStr = "abcde";
let str1 = newStr.match(/[^str]/);
console.log(str1[0]);

Why it returns “a”.
How to use variable name as regex.

You have to build it using RegExp

const str = "abce";
const newStr = "abcde";
const re = new RegExp('[^' + str + ']');
const str1 = newStr.match(re);
console.log(str1[0]); // d
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.