0
我有以下正则表达式,它决定(我希望)如果一个字符串是一个URL或不是。JavaScript正则表达式在执行后有不同的结果
/^(((\/[\w-]+)+\/?)|(((http|ftp|https):\/\/)[\w-]+))((\.[\w-]+)?([\w.,@?^=%&lL\/~+#-]*[\[email protected]?~=%&:\/~+#-])?)$/gi
我发现是,如果我是正则表达式保存到一个对象,然后测试相同的字符串两次,我得到两个不同的结果显示在此的jsfiddle
https://jsfiddle.net/gpc5trsw/
中的代码此琴是这样的:
var test = /^(((\/[\w-]+)+\/?)|(((http|ftp|https):\/\/)[\w-]+))((\.[\w-]+)?([\w.,@?^=%&lL\/~+#-]*[\[email protected]?~=%&:\/~+#-])?)$/gi
var str = "/api/WebTest";
document.getElementById("firstCtr").innerHTML = /^(((\/[\w-]+)+\/?)|(((http|ftp|https):\/\/)[\w-]+))((\.[\w-]+)?([\w.,@?^=%&lL\/~+#-]*[\[email protected]?~=%&:\/~+#-])?)$/gi.test(str)
document.getElementById("secondCtr").innerHTML = /^(((\/[\w-]+)+\/?)|(((http|ftp|https):\/\/)[\w-]+))((\.[\w-]+)?([\w.,@?^=%&lL\/~+#-]*[\[email protected]?~=%&:\/~+#-])?)$/gi.test(str)
document.getElementById("first").innerHTML = test.test(str)
document.getElementById("second").innerHTML = test.test(str)
具有以下HTML:
<div>
First Run Control: <span id="firstCtr"></span>
</div>
<div>
Second Run Control: <span id="secondCtr"></span>
</div>
<hr/>
<div>
First Run: <span id="first"></span>
</div>
<div>
Second Run: <span id="second"></span>
产生的HTML输出是这样:
首次运行控制:真
第二运行控制:真
首次运行:真
第二次运行:false
为什么测试结果第二次在对象版本上测试时发生了变化? JavaScript可能会是一个残酷的情妇有时......
[删除'g'标志](https://jsfiddle.net/tusharj/gpc5trsw/1/) – Tushar