1

I have a text like

string 1 : 
I am a text and this is a youtube video https://www.youtube.com/watch?v=j82FBbgpUy4 !!!

I would like to extract the youtube video url from the string and return it.

Result :

string 2 :
https://www.youtube.com/watch?v=j82FBbgpUy4

Is there another way more efficient than spliting the string by spaces and searching in the array if it contains "https://www.youtube.com/watch?v=" (it's not the best way to do it)? I cannot find any other solution

jiji
  • 337
  • 2
  • 3
  • 13
  • 1
    Your approach sounds acceptable to me. Unless there are extra nitpicky requirements, it should work fine. Optimize later if you deem it necessary. – byxor Jun 14 '17 at 13:23
  • See [this question](https://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript) if you want a regex based solution. – Saravana Jun 14 '17 at 13:29

1 Answers1

1

So. I found this regular expression http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?, here, which seems to work.

Once you have that, all you have to do is this:

var re = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/;
var str = "I am a text and this is a youtube video https://www.youtube.com/watch?v=j82FBbgpUy4 !!!"
var url = re.exec(str)['0']

Then url should have the video url.

Adam LeBlanc
  • 932
  • 7
  • 21
  • This regular expression covers a bit more than the example URL you gave though. You can just find/make one that covers only the URLs you want to match though if you need to restrict it to the format you gave. – Adam LeBlanc Jun 14 '17 at 13:47
  • There is a problem with `var url = re.exec(str)['0']`, it returns error `Error :TypeError: Cannot read property '0' of null(…)` if `str` doesn't contain any valide url, I can't find how to solve it – jiji Jun 15 '17 at 08:56
  • Just check if it's null first. Just have an if checking `re.exec(str) == null` if it's true, then it's not there. – Adam LeBlanc Jun 16 '17 at 12:38