I just stumbled over this very strange behavior. I have a regex that extracts Youtube video IDs from embedded iframes. The regex looks like this:
var regex = /(?:youtu\.be|youtube\.com|ytimg\.com|youtube-nocookie\.com).*(?:\/|\?v=|\&v=|\?video_id=|\&video_id=)([\w\-_]{11})[^\w\-_]?/ig;
I now have an embedded Youtube iframe that looks like this:
<iframe id="ytplayer" type="text/html" width="300" height="200"
src="//www.youtube.com/embed/M7lc1UVf-VE?autoplay=0&origin=//example.com"
frameborder="0"/>
As you can see, that regex should match against the src
attribute of this element. However, if I do the following code it will return false
:
regex.test( $('#ytplayer').attr('src') );
You will say "Well, your regex is obviously wrong, check it again". But then have a look at this:
regex.test( $('#ytplayer').attr('src').toString() );
This will return true
even though it is the exact same code, only with an added toString()
. And yes, .attr('src')
already returns a string! Why is this? I can reproduce this in Chrome and Firefox so it's most likely not a bug in a JS implementation.
(You can find a JsFiddle to try it out here)