我需要从字符串中替换url。
示例:
var container = "hello http://www.youtube.com/watch?v=r94hrE10S84 hello";
我想替换为:
container = "hello <iframe src='//www.youtube.com/embed/r94hrE10S84' </iframe> guys";
我想做:
container = container.replace("http://www.youtube.com/watch?v=(/\w*\d+\w*/)","<iframe src='//www.youtube.com/embed/$1' </iframe>");
谢谢
答案 0 :(得分:1)
container.replace(/(https?:\/\/\S+)/i, "<iframe src='$1' </iframe>");
答案 1 :(得分:0)
您可以使用:
repl = container.replace(/(https?:\/\/\S+)/i, function(m) {
if (m.indexOf(".youtube."))
return m.replace(/^(.+?)\/watch\?v=(.+)$/, "<iframe src='$1/embed/$2'> </iframe>");
else return m;
});
//=> ello <iframe src='http://www.youtube.com/embed/r94hrE10S84'> </iframe> hello
答案 2 :(得分:0)
(?:https?://)?(?:www\.)?youtu(?:be\.com/watch\?(?:.*?&(?:amp;)?)?v=|\.be/)([\w\-]+)(?:&(?:amp;)?[\w\?=]*)?
ID应该在第一组。
所以你的代码就像:
var container = "http://www.youtube.com/watch?v=r94hrE10S84";
var reg = /(?:https?:\/\/)?(?:www\.)?youtu(?:be\.com\/watch\?(?:.*?&(?:amp;)?)?v=|\.be\/)([\w\-]+)(?:&(?:amp;)?[\w\?=]*)?/;
container = container.replace(reg,"<iframe src=\"//www.youtube.com/embed/$1\"></iframe>");
这甚至考虑了没有www,w / o协议和短链接的链接(youtu.be)