将regex $1和$2保存为javascript变量

save javascript .replace regex $1 and $2 as javascript variables

本文关键字:javascript 保存 变量 regex      更新时间:2023-09-26

我有多个视频编码器的问题。我试图保存嵌入url作为变量在以后的时间使用。

编码器从带有文本的div中获取视频信息。

<div class="text">hey check this video out! youtube.com/watch?v=123456</div>
$('.text').html(function(i, html) {
var videoAddress = html.replace(/(?:http:'/'/|https:'/'/)?(?:www'.)?(?:youtube'.com|youtu'.be)'/(?:watch'?v=)?(.*?)([^'s]+)/g, '$2').replace(/(?:http:'/'/)?(?:www'.)?(?:vimeo'.com)'/(.+)/g, '$1');
});  

我想要的输出是:

var embedCode = [Either $1 or $2];

我到处找都找不到解决办法。这是可能的regex和javascript?

你可以这样做:

var arr = [];
var str = "hey check this video out! youtube.com/watch?v=123456 and there is some other text youtube.com/watch?v=3t_3456 and some more.";
var re = /youtube'.com'/watch'?v=([^'s]+)/g;
while (match = re.exec(str)) {
  arr.push(match[1]);
}
console.log(arr);