user4353985
user4353985

Reputation:

parse youtube video id from string with javascript

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>');
}

Upvotes: 1

Views: 2006

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

Try this:

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

REGEX DEMO

Upvotes: 1

Related Questions