1

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

Delimitry
  • 2,987
  • 4
  • 30
  • 39
MrVila
  • 95
  • 9

3 Answers3

1
container.replace(/(https?:\/\/\S+)/i, "<iframe  src='$1' </iframe>");
0

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0
(?: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)

Fiddle

Source

Community
  • 1
  • 1
Antonio E.
  • 4,381
  • 2
  • 25
  • 35