javascript - 为什么在 Chrome 中有效的正则表达式在 Poltergeist/PhantomJS 中不起作用?

标签 javascript regex google-chrome phantomjs poltergeist

我对一些旨在解析链接的 javascript 有问题(以便在适当的情况下嵌入视频播放器)。在 Chrome 中手动测试时它工作得很好,但是当我在不同的浏览器中运行自动化测试套件时,它就不行了。

var n = childNodes[i];
var html = n.nodeValue;

var urlVimeo0 = /http:\/\/(www\.)?vimeo\.com\/(\d+)($|\/)/;
var urlVimeo1 = /http:\/\/(www\.)?vimeo\.com\/(\d+)($)/;
var urlVimeo2 = /http:\/\/(www\.)?vimeo\.com\/(\d+)(\/)/;
var urlVimeo3 = /http:\/\/(www\.)?vimeo\.com\/(\d+)$/,
var urlVimeo4 = /http:\/\/(www\.)?vimeo\.com\/(\d+)\//,
var urlVimeo5 = /http:\/\/(www\.)?vimeo\.com\/(\d+)/;

// Comments show output when run in Poltergeist/PhantomJS
console.log('"'+html+'"'); // "http://vimeo.com/26278283​"
console.log(html.match(urlVimeo0)); // null
console.log(html.match(urlVimeo1)); // null
console.log(html.match(urlVimeo2)); // null
console.log(html.match(urlVimeo3)); // null
console.log(html.match(urlVimeo4)); // null
console.log(html.match(urlVimeo5)); // http://vimeo.com/26278283,,26278283

// Output in Chrome (same order)
// "http://vimeo.com/26278283" 
// ["http://vimeo.com/26278283", undefined, "26278283", "", index: 0, input: "http://vimeo.com/26278283"] 
// ["http://vimeo.com/26278283", undefined, "26278283", "", index: 0, input: "http://vimeo.com/26278283"] 
// null 
// ["http://vimeo.com/26278283", undefined, "26278283", index: 0, input: "http://vimeo.com/26278283"] 
// null
// ["http://vimeo.com/26278283", undefined, "26278283", index: 0, input: "http://vimeo.com/26278283"] 

原始的 (urlVimeo0) 在 Chrome 中工作,但是当我使用 Poltergeist 将其作为测试套件的一部分运行时,当该位后面有任何与数字匹配的内容时,什么都不起作用。两者都是基于 webkit 的,所以我不知道为什么美元/斜线会导致失败。

最佳答案

TL;DR 转义美元符号 /foo\$/,PhantomJS 使用非常旧的 Webkit 版本,对正则表达式语法的支持与 Chrome 不同。

--

您有两个潜在的问题。

第一个是您对 $ 的使用;请注意,在正则表达式中,它表示字符串的结尾(^ 表示字符串的开头)。因此 /foo$/ 将匹配 "a_foo"不会匹配 "foo_a",并且不会匹配"foo$" 也可以。

如果您实际上想匹配字符串中的美元符号,则需要对其进行转义:/foo\$/

第二个问题是,虽然 PhantomJS(Poltergeist 在后台使用)基于 Webkit,但它是一个古老的、糟糕的、仅由 PhantomJS 使用的 Webkit 的 fork 版本,并且缺少很多东西现代功能,包括正则表达式语法的各种扩展。因此,您会发现 Chrome 对正则表达式的解释与 PhantomJS 的解释之间存在一些差异。

如果您想深入了解可用的浏览器兼容性表/规范,您可以从这里开始:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Specifications 。 ECMAScript 3 规范中提供的任何内容都可能在 PhantomJS 中提供。之后发生的任何事情都是可疑的。

关于javascript - 为什么在 Chrome 中有效的正则表达式在 Poltergeist/PhantomJS 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012543/

相关文章:

JavaScript RegExp 用于电话号码验证,需要在数字之间允许连字符和空格

mysql - 在 MySql 正则表达式查询中使用变量

javascript - 选择一个div的所有内容

javascript - Javascript函数错误中的继承

javascript - $ ("input[type=username]").val() 返回未定义

javascript - react : How to pass an array as props and render a list of images?

css - 为什么谷歌浏览器不会自动中断?

javascript加载条件语句

python - 为文本文件上的每个单词和符号添加引号

WPF:如何在WPF/MVVM中制作Google Chrome样式的GUI?