1

I have an problem with constructing regex from variable.

var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\(2n\+1\)';

console.log(selector.test(a))//true

var reg = new RegExp(s,"g");
console.log(reg.test(a) )//false

Second is false because I have string quotes around it (I think), how do I construct regexp from string?

https://jsfiddle.net/eq3eu2e8/1/

1
  • 2
    You have to use double-\ in the regular expression string: '.playlist-item:nth-child\\(2n\\+1\\)' Commented Jul 17, 2016 at 14:09

1 Answer 1

3

For a string you have to use double backslashes if you want to include them in the string:

var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\\(2n\\+1\\)';

console.log(selector.test(a)); //true

var reg = new RegExp(s,"g");
console.log(reg.test(a)); //false
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.