2011-11-13 34 views
1

我的理解是,可以在JavaScript中使用两种方法中的任意一种对基于区分大小写的正则表达式匹配:match(/pattern/i)match("pattern","i")。虽然我没有得到第二个变体在Chrome中工作。 (我正在使用Chromium 14.0.835.202)。这是Chrome中的错误吗? (或用户错误?)Chrome手柄是否正确匹配?

在Firefox中,当我运行此代码时,我得到:Hello World和Hello World。在Chrome中,我获得了Hello World,未定义。

<html> 
<head> 
</head> 
<body> 

<input type="button" id="button" value="Click me!" onclick="buttonClick()" /> 

</body> 

<script language="javascript"> 
function buttonClick() 
{ 
    str="Hello World" 
    alert(str.match(/hello world/i)) 
    alert(str.match("hello world","i")) 
} 
</script> 
</html> 

回答

6

不,这不是一个错误。 Firefox允许使用String.match中的flags参数,但正如Mozilla文档中所指出的那样(或者更确切地说,因为它使用的需要注意 - this functionality is no longer even mentioned)它是非标准的,应该避免。而且,它通常效率较低。

如果您需要此功能,请改为使用new RegExp

+2

并且[ECMAscript v5.1规格](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)的第145页没有提及第二个参数'.match()' – jfriend00

+0

谢谢。正是我需要的。 – snowguy