How to get youku video id from url by regex?

2.7k Views Asked by At

I need to get youku video id from url by regex, for example:

http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html

I only need XNTg3OTc3MzY4 to keep in a variable.

How can I write it in function below

var youkuEmbed = "[[*supplier-video]]";

var youkuUrl = youkuEmbed.match(/http://v\.youku\.com/v_show/id_(\w+)\.html/);

I tried this but it didn't work.

Thanks!

4

There are 4 best solutions below

0
On

It looks like you need to escape all the slashes because that's the delimiter for the regex itself:

var youkuUrl = youkuEmbed.match(/http:\/\/v\.youku\.com\/v_show\/id_(\w+)\.html/);

Then use the first capture group, as Unihedron stated.

0
On

You can use this regex:

http://v\.youku\.com/v_show/id_(\w+)\.html

Your match is in the first capturing group.

Here is a regex demo.

0
On

You can use a simple regex like this:

id_(\w+)

Working demo

enter image description here

The idea is to match the _id and the capture all the alphanumeric strings.

MATCH 1
1.  [29-42] `XNTg3OTc3MzY4`

If you go the Code Generator section you can get the code. However, you can use something like this:

var myString = 'http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html';
var myRegexp = /id_(\w+)/;
var match = myRegexp.exec(myString);
alert(match[1]);  
//Shows: XNTg3OTc3MzY4
0
On

Id the id always follows id_, you could possibly split the string.

'http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html'.split(/.*id_|\./)[1]
//=> 'XNTg3OTc3MzY4'

For this specific string, you could just do.

'http://youku.com/id_XNTg30Tc3MzY4.html'.split(/id_|\./)[2]
//=> 'XNTg3OTc3MzY4'