Drifference in writing regex

When I write

let str = "bermuda";
let ser = /a$/;
console.log(str.search(ser));
result is 6

but When I write

let str = "bermuda";
let res = "a";
let ser = /res$/;
console.log(str.search(ser));

result is -1

Please tell me why it isn’t returning position of “a” When I am using veriable

Use new RegExp(string) to build a regular expression dynamically. The literal /.../ form cannot be used with dynamic content.

let str = "bermuda";
let res = "a";
let ser = new RegExp(res + "$");
console.log(str.search(ser));

Thanks for your answer. But I didn’t understand why you use (res+"$")…can’t we use (res+$)…like we normally did in /a+$/. I mean why use quotes?

new RegExp(string) takes string as an argument.
res is a variable
"$" is a string
And I am concatenating them both into a string res + "$"
If I wouldn’t surrounded $ with quotes JS would think that I’m looking for variable named $

1 Like

The regex /res+$/ matches the literal word “re” followed by any number of the letter ‘s’, at the end of the string. Think of the /foo/ syntax as acting sort of like quotes. Like @orvalho said, you need to use the RegExp constructor to construct regexes out of variables.

1 Like

Ok, thanks now I understand

1 Like