尝试从格式为“Chrome/34.0.1847.116”的 Chrome 用户代理中提取版本。
这是有效的:
userAgent.match(/.*Chrome.*?([\d|\.]*)\s/i);
这是行不通的(我正在努力让它工作):
var versionRegularExpression = new RegExp('.*'+'Chrome'+'.*?([\d|\.]*)\s', 'i');
userAgent.match(versionRegularExpression);
我一定是错误地格式化了我的新 RegExp - 谁能告诉我我是怎么搞砸的?
完整的用户代理是:
var userAgent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';
当您使用 RegExp
对象而不是 RegEx 文字时,您还需要对 \
进行转义,
new RegExp('.*'+'Chrome'+'.*?([\\d|\\.]*)\\s', 'i');
此外,Chrome
不需要连接,它可以是单个字符串文字的一部分,就像这样
new RegExp('.*Chrome.*?([\\d|\\.]*)\\s', 'i');
作为Paulpro points out in the comments section ,当您使用字符类时, |
将被视为允许的字符之一,而不是 OR 运算符。所以,你在那里不需要它
new RegExp('.*Chrome.*?([\\d\\.]*)\\s', 'i');
引自MDN's RegExp page ,
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");