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/

Toniq
  • 4,492
  • 12
  • 50
  • 109
  • 2
    You have to use double-\ in the regular expression string: `'.playlist-item:nth-child\\(2n\\+1\\)'` – Pointy Jul 17 '16 at 14:09

1 Answers1

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
Jacques Marais
  • 2,666
  • 14
  • 33