昨天'Hnatt'非常友好地提供了这个剧本的正则表达式部分:
<html>
<body>
<script type="text/javascript">
alert("hhhhhh yadad example.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/)[1]);
alert('alert 2');
</script>
</body>
</html>
现在我有了一个新的问题/问题/ point_of_confusion。如果我将“example.com”更改为不匹配,则整个脚本会停止。我想知道一个解决方案,然后尝试/ catch,允许脚本继续前进。 (虽然,我用try / catch攻击修复,插入try catch /打破更大的脚本......我不知道为什么。这就是为什么我想要一个不包含try / catch的解决方案)。我还想尝试理解为什么当'匹配'功能找不到匹配时会发生这种拖拽。
<html>
<body>
<script type="text/javascript">
alert("hhhhhh yadad exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/)[1]);
alert('alert 2');
</script>
</body>
</html>
这是一个简化的版本。在更广泛的脚本中,我使用大海捞针中找到的针并将其分配给变量。
答案 0 :(得分:7)
当没有匹配时,.match()
方法返回null。当您尝试获取[1]
的索引null
时,会出现错误,暂停脚本。您应该检查一下,例如:
var match = "hhhhhh yadad exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/);
if (match) {
alert(match[1]);
}
alert('alert 2');
答案 1 :(得分:1)
如果您不想生成脚本错误而不使用try / catch,那么您需要将匹配返回值分配给变量并测试它以查看是否找到匹配项以及是否在使用之前找到了足够的匹配项
var matches = "hhhhhh yadad exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/);
if (matches && matches.length > 1) {
alert(matches[1]);
}
答案 2 :(得分:0)
Jeremy解释了为什么你会收到这个错误。您可以确保索引操作有效,如下所示:
alert(("hhhhhh yadad exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/) || [])[1]);
如果匹配失败,这会将匹配结果变为空数组。