【问题标题】:Javascript regex test from variable [duplicate]来自变量的Javascript正则表达式测试[重复]
【发布时间】:2016-11-20 04:44:57
【问题描述】:

我在从变量构造正则表达式时遇到问题。

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

第二个是假的,因为我在它周围有字符串引号(我认为),我如何从字符串构造正则表达式?

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

【问题讨论】:

  • 你必须在正则表达式字符串中使用双-\:'.playlist-item:nth-child\\(2n\\+1\\)'

标签: javascript regex


【解决方案1】:

对于一个字符串,如果你想将它们包含在字符串中,你必须使用双反斜杠:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2015-01-21
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多