我有一个变量数组,所有变量都包含文本。我只想选择包含分秒标记的项目,例如。 “3:00”、“4:01”、“0:23”。我了解如何遍历数组,我只需要知道如何实现 this regex .
为了安全起见,这里是:
^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])| ([0-5][0-9]))$
我正在努力实现它:
$.each(comments, function(i, val) { //Go through array with jQuery
//Remove from array if instance of "minute:second" is not found
});
谢谢!
编辑:
Dave Thomas 要求提供示例。它们都是 YouTube 评论。下面是带有 minute:time 和没有的评论示例。全部取自示例视频。
- “1:00 Fifa 12 评论员?”
- “ROOOOOOOOONEY <3”
编辑2:
for (var i = 0, len = comments.length; i < len; i++) {
if(!(comments[i].test(/(([0-5][0-9])|[0-9])\:[0-9]{2,2}/))){
comments.splice(i,1);
}
}
最佳答案
您需要使用 native filter fitlering 数组的函数(链接中有一个适用于旧版浏览器的垫片)而不是 each ,您可以使用 test 测试针对字符串的正则表达式:
var pattern = /(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))/;
comments = comments.filter(function(str){
return pattern.test(str);
});
关于Javascript/jQuery 使用正则表达式搜索 "minute:second"时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10974121/