【问题标题】:Why does the statement if ( !condition ) { console.log(condition) } display true [duplicate]为什么语句 if ( !condition ) { console.log(condition) } 显示 true [重复]
【发布时间】:2014-01-29 08:09:02
【问题描述】:

我想做一个 String 方法,它接受一个 RegExp 和一个回调,然后通过 RegExp 拆分 String,并将回调的返回插入到拆分数组中。简而言之,它会做这样的事情:

"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
    => [a, 2, b, 3, c]

如果字符串与正则表达式不匹配,它应该返回一个数组,如下所示:

"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
    => ["a b c d e"]

我写了这段代码,但它并没有像我想象的那样工作:

String.prototype.preserveSplitReg = function(reg, func) {

    var rtn = [], 
        that = this.toString();
    if (!reg.test(that)) {
        console.log(reg, that, reg.test(that));
        return [that];
    }

    ...
}

只有当字符串与reg 不匹配时才应调用console.log,对吗?但有时它会记录(reg, that, true)。那个麻烦的字符串和reg是:

"See <url>http://www.w3.org/TR/html5-diff/</url> for changed elements and attributes, as well as obsolete elements and"
/<url>.*?<\/url>/g

控制台记录为真。我不知道为什么。任何帮助将不胜感激。

【问题讨论】:

  • 你能用这个小提琴复制吗? jsfiddle.net/QN8MT
  • theCoder:我对小提琴不友好。修改了你的建议,它看起来像工作......
  • 菲利克斯:这很有趣。我注意到 \d 和 [0-9] 之间的细微差别

标签: javascript regex


【解决方案1】:

这是due to a bug in Javascript RegEx engine (ECMAScript3)

基本上带有g 修饰符的正则表达式无法正确重置,因此多个test() 调用在true and false 之间切换。

【讨论】:

  • 似乎我应该使用递归函数,而不是 /g。谢谢
  • 是的那会更好,否则不要依赖测试方法使用匹配可能。
猜你喜欢
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 2019-04-04
相关资源
最近更新 更多