gpt4 book ai didi

javascript - 使用 jQuery 从 URL 获取 YouTube 视频 ID

转载 作者:数据小太阳 更新时间:2023-10-29 06:08:41 28 4
gpt4 key购买 nike

我正在尝试将任何 YouTube URL 作为输入的文本区域输入,并像 Facebook 一样嵌入视频。

我有:

var text = $('#content').val().split(' ');
for (i = 0; i < text.length; i++) {
var test = text[i].indexOf('youtube.com/watch');
var check = text[i].indexOf('[youtube=');

if (test != -1 && check == -1) {
var ytid = text[i].substring(text[i].lastIndexOf('=') + 1);
text[i] = '[youtube=' + ytid + ']';
}
}
var boxval = text.join(' ').trim();

它接受任何 YouTube URL 并将其变成 [youtube=videoid] .那么问题是,当提交带有 <br> 的 URL 时或 \n最后它添加了 ]然后。

有人知道更好的方法吗?

最佳答案

最近有人提出了类似的问题(但该问题需要 PHP 解决方案)。这是 my solution to that question 的 JavaScript 版本:

// Linkify youtube URLs which are not already links.
function linkifyYouTubeURLs(text) {
/* Commented regex (in PHP syntax)
$text = preg_replace('%
# Match any youtube URL in the wild.
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w\-]{10,12}) # $1: Allow 10-12 for 11 char youtube id.
\b # Anchor end to word boundary.
[?=&\w]* # Consume any URL (query) remainder.
(?! # But don\'t match URLs already linked.
[\'"][^<>]*> # Not inside a start tag,
| </a> # or <a> element text contents.
) # End negative lookahead assertion.
%ix',
'<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',
$text);
*/
// Here is the same regex in JavaScript literal regexp syntax:
return text.replace(
/(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w\-]{10,12})\b[?=&\w]*(?!['"][^<>]*>|<\/a>)/ig,
'<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');
}

您可以轻松修改替换字符串以转换为 BBCode 而不是 HTML。

关于javascript - 使用 jQuery 从 URL 获取 YouTube 视频 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5429731/

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