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

3 Answers 3

1
container.replace(/(https?:\/\/\S+)/i, "<iframe  src='$1' </iframe>");
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Ty but it don't change watch?v= for embed/ and I only want change url of youtube.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.