Reputation: 93
I need replace url from a string.
example:
var container = "hello http://www.youtube.com/watch?v=r94hrE10S84 hello";
I want replace to:
container = "hello <iframe src='//www.youtube.com/embed/r94hrE10S84' </iframe> guys";
Im trying to do:
container = container.replace("http://www.youtube.com/watch?v=(/\w*\d+\w*/)","<iframe src='//www.youtube.com/embed/$1' </iframe>");
thank you
Upvotes: 1
Views: 129
Reputation: 4401
(?:https?://)?(?:www\.)?youtu(?:be\.com/watch\?(?:.*?&(?:amp;)?)?v=|\.be/)([\w\-]+)(?:&(?:amp;)?[\w\?=]*)?
ID Should be on first group.
So your code will be like:
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>");
This take into account even link w/o www, w/o protocol and short links (youtu.be)
Upvotes: 0
Reputation: 786081
You can use:
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
Upvotes: 0
Reputation: 997
container.replace(/(https?:\/\/\S+)/i, "<iframe src='$1' </iframe>");
Upvotes: 1