gpt4 book ai didi

javascript - 如何使此youtube videoId解析RegExp在JS中工作?

转载 作者:行者123 更新时间:2023-12-03 06:27:59 24 4
gpt4 key购买 nike

我正在尝试使用此处介绍的出色RegEx来从任何youtube类型的url中获取视频ID:

parse youtube video id using preg_match

// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();

var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;

console.log('vid: '+videoId);

我的控制台总是给我一个 null videoId。我在正则表达式变量中错误地转义了某些内容吗?我添加了第二个反斜杠以避开单个反斜杠。

抓我的头?

最佳答案

%是从中获得链接的PHP的分隔符,使用new RegExp()时Javascript不希望使用分隔符。另外,看起来\\.可能应该替换为\.尝试:

var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');

另外,您可以使用Javascript的 /.../分隔符从字面上创建正则表达式,但是随后您需要转义所有 /:
var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;

Documentation

更新:

快速更新以解决对字面量表达式( /ab+c/)与构造函数( new RegExp("ab+c"))效率的评论。该文件说:

Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.



和:

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.



由于您的表达式将始终是静态的,因此我会说从字面上创建它(第二个示例)会稍快一些,因为它是在加载时进行编译的(但是,请勿混淆以为它不会创建 RegExp对象)。这个小差异可以通过 quick benchmark test确认。

关于javascript - 如何使此youtube videoId解析RegExp在JS中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23837578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com