MrVila
MrVila

Reputation: 93

Javascript replace using regular expression

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

Answers (3)

Antonio E.
Antonio E.

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)

Fiddle

Source

Upvotes: 0

anubhava
anubhava

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

Vahid Taghizadeh
Vahid Taghizadeh

Reputation: 997

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

Upvotes: 1

Related Questions