Search code examples
javascriptjqueryyoutubesrc

Extract iframe src before character


I am selecting this iframes src

<iframe src="http://www.youtube.com/embed/Y44_kWSoiPc?rel=0" frameborder="0" allowfullscreen></iframe>

using

var youtubesrc = $('iframe[src^="http://www.youtube.com/embed/"]').attr('src');

which returns http://www.youtube.com/embed/Y44_kWSoiPc?rel=0.

But I only want the src before the ? (question mark) so that in this case it will return http://www.youtube.com/embed/Y44_kWSoiPc, which is before the ?.

How can this be done?


Solution

  • Change the line into:

    var youtubesrc = $('iframe[src^="http://www.youtube.com/embed/"]').attr('src').split('?')[0];
    

    You will split the string into parts separated by ? and then take 1st part which is everything from the start of the string until ?.

    And if there is no ? in the string then split('?')[0] will contain whole string, so you don't have to check if the URL contains ?.