2011-07-13 58 views
1

尝试在一个新匹配中使用匹配函数的结果时出现问题。JavaScript中的重复匹配

这是代码:

<html> 
<body> 

<script type="text/javascript"> 

p="somelongtextmelongtextmelongtextmelongtext"; 

f1 = p.match(/some/g); 

document.write(f1); 

f2 = f1.match(/om/g); 

document.write(f2); 

</script> 

</body> 
</html> 

输出是单词“一些”时,它必须是“嗡”。我不明白这种行为,我需要在更复杂的情况下输出f1。

在此先感谢。

回答

6

您确定您粘贴了与您测试的完全相同的代码吗?

我问,因为f1 = p.match(/some/g);返回一个匹配数组,而Array对象没有.match方法,所以f1.match(/om/g);应该抛出一个错误。

不管怎么说,要做到这一点正确的做法是:

p="somelongtextmelongtextmelongtextmelongtext"; 
f1 = p.match(/some/g); 
if (f1) { 
    f2 = f1[0].match(/om/g); 
    console.log(f2); 
} 
+0

是的。这就是代码。我很困惑,因为我总是看到结果是一个字符串,因为格式是match1,match2等......和document.write(f1);显示有效的输出而不使用数组格式。非常感谢你。 – Memochipan

+0

使用控制台比使用document.write测试东西要好。它会显示一个数组,而不是数组的toString()等价物。 – epascarello

+0

编辑我的答案使用'console.log' per @ epascarello的评论 – digitalbath

0

的输出为 “一些”,因为它是在线路出现故障:F2 = f1.match(/ OM /克);它永远不会写入f2。

f1是一个对象变量,而不是一个字符串。该对象没有匹配方法。用下面的代替行:

f2 = f1.toString()。match(/ om/g);

HTH

+0

由于'.match()'方法可能会返回一个包含多个匹配的数组,并且'Array.toString()'将所有匹配与逗号字符连接在一起,使得发送'.match'可能匹配你不想要的东西。 – digitalbath