解析Youtube网址

时间:2018-03-21 13:15:41

标签: javascript regex youtube

我试图从字符串中获取所有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。我做错了什么?

4 个答案:

答案 0 :(得分:1)

假设v =某事,试试这个(来自Extract parameter value from url using regular expressions的正则表达式)

ID

答案 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))