You are constructing the regular expression by passing a string to the RegExp constructor.
\
is an escape character in string literals.
The \
is consumed by the string literal parsing…
const foo = "foo";
const string = '(\s|^)' + foo;
console.log(string);
… so the data you pass to the RegEx compiler is a plain s
and not \s
.
You need to escape the \
to express the \
as data instead of being an escape character itself.