2

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]);

1
  • in other words - you need to escape the escape character. Commented Oct 29, 2017 at 9:59

1 Answer 1

2

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");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.