我试图从字符串中获取所有Youtube视频ID:
https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg
关注this answers我写了代码:
var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)/g,
str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg',
match;
while (match = re.exec(str)) {
if (match.index === re.lastIndex) {
re.lastIndex++;
}
console.log(match[1]);
}
但console.log
仅显示最后一个ID 97aiSGxmizg
。我做错了什么?
答案 0 :(得分:1)
答案 1 :(得分:1)
根据发布的字符串格式v=id
,可以做一些简单的事情,就像在空格分割字符串一样简单,再与
reduce()
结合使用, v=
,以获得成功分割的ID。
我还使用匿名函数(function(){...})();
只需要运行拆分一次。
Stack snippet
var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg';
var list = str.split(' ').reduce(function(r, e) {
(function(i){
if (i.length > 1) r.push(i[1]);
})(e.split('v='));
return r;
}, []);
console.log(list);

如上所述,如果有其他格式,可以轻松使用正则表达式,例如
Stack snippet
var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg http://www.youtube.com/v/-wtIMTCHWuI http://youtu.be/-DOQsYk8cbnE';
var list = str.split(' ').reduce(function(r, e) {
(function(i){
if (i.length > 1) r.push(i[1]);
})(e.split(/v=|v\/-|be\/-/));
return r;
}, []);
console.log(list);

答案 2 :(得分:0)
捕获组仅匹配该字符串中的最后一个匹配。
将字符串拆分为数组并将其记录在那里:
var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)/g,
str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg',
strs = str.split(' ');
strs.forEach((str) => {
var match;
while (match = re.exec(str)) {
if (match.index === re.lastIndex) {
re.lastIndex++;
}
console.log(match[1]);
}
})
答案 3 :(得分:-1)
你的正则表达式不正确。
正确的正则表达式是这样的:
var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?[^ ]*v=)([a-zA-Z0-9\-_]+)/g;
var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs jiberish https://www.youtube.com/watch?v=DOQsYk8cbnE jiberish a https://www.youtube.com/watch?v=97aiSGxmizg'
console.log(str.match(re))