I have this RegExp: var myReg = RegExp("https?://www.youtube.com/watch\?v=[^\"]+",""); to find the youtube link within a string. I then want to make the part of the string matching the RegExp a variable; lets say var url = "part of string matching the RegExp"
then I coudl do something like window.location = url; to redirect the browser directly to the video page. Thanks
Add a comment
|
2 Answers
You only have to access the first element of the result, if any:
var r = string.match(myReg);
if(r) var url = r[0];
Take care because is you dont find the url, the result will be a null value
2 Comments
Samuel Charpentier
I let you see the full thing, its not working properly look : jsfiddle.net/a99Ln/3
durum
Your regexp doesnt match the url, it returns a
null value. I tried with var myReg = /https?:\/\/www\.youtube\.com\/watch\?v=[^"]+/; and worked fine.This should do the trick:
myReg.exec(str);
var url = RegExp.lastMatch;
Udi
3 Comments
Samuel Charpentier
I let you see the full thing, its not working properly look : jsfiddle.net/a99Ln/3
Udi Cohen
it is because the RegExp is not working as you expected. The RegExp evaluation returns null... check your input / RegExp
Samuel Charpentier
the Reg does work, if you try to alert(plainText) on my example it works