Q:

Regular Expression from String gives null in Javascript

I have a string 
let str = 'WordA<br>WordB';
I am using this expression /(\S+)(?=<br>)/ to match characters before the <br>.
It works fine directly as a predefined function 
let regex = /(\S+)(?=<br>)/;
But when I try to build it using a string, it gives null everytime.
let rgs = "(\S+)(?=<br>)";
let regex = new RegExp(rgs);

How to use the regex as a string to obtain the same results.
Full code:

let str = 'WordA<br>WordB';
let regex = /(\S+)(?=<br>)/;

let m = str.match(regex);
console.log(m);
console.log(m[1]);

let rgs = ("(\S+)(?=<br>)");
let regex2 = new RegExp(rgs);
let m2 = str.match(regex2);
console.log(m2);
console.log(m2[1]);

A:

When using regex in string via new RegExp(), you need to escape the backslash character:

let str = 'WordA<br>WordB';
let regex = /(\S+)(?=<br>)/;

let m = str.match(regex);
console.log(m);
console.log(m[1]);

let rgs = "(\\S+)(?=<br>)";
let regex2 = new RegExp(rgs);
let m2 = str.match(regex2);
console.log(m2);
console.log(m2[1]);

Otherwise the "\S" is translated to just "S" (as you are escaping the S character):

console.log("S", "\S", "\\S", "S" === "\S");

