1

hello I found lots of threads here which explains how to parse youtube id from url but nothing I found which can extract youtube video id from string.

I need a function which can return me youtube video id from url

For Example I have string

> Hello this is my string and this is my youtube video : http://youtube.com/w=abcdef and this is my blog http://stackoverflow.com etc etc.

and it should return

> Hello this is my string and this is my youtube video : abcdef and this is my blog http://stackoverflow.com etc etc.

Trying this function but not working properly

function linkifyYouTubeURLs(text) {
    var re = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
    return text.replace(re,
        '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');
}
5
  • 2
    Mr Gates, would you be kind enough to provide and example of one function your tried? :-) Commented Apr 22, 2015 at 5:21
  • 1
    sure 1 min. I'll edit Commented Apr 22, 2015 at 5:21
  • How did you get the link http://youtube.com/w=abc, you sure it is correct? I tried replacing "abc" with video id and the link is still not working. Commented Apr 22, 2015 at 5:47
  • sorry correct link is : youtube.com/watch?v=bRnm8f6Wavk Commented Apr 22, 2015 at 5:48
  • linkifyYouTubeURLs( "My youtube video : http://youtube.com/watch?v=bRnm8f6Wavk and my blog etc." ) gives me your expected result. What is the real problem? Commented Apr 22, 2015 at 5:54

1 Answer 1

1

Try this:

var re = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;

REGEX DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

it would be great if you can provide me some example as I tried so many regex before and it works but can't get my expected output

Your Answer

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