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

Why? Because your regular expression matches a single character that is not an s, a t, or an r. in newStr. The first letter that matches is the a.

1 Like