javascript - RegExp.match doesn't match on jQuery.attr result while it should -


i stumbled on strange behavior. have regex extracts youtube video ids embedded iframes. regex looks this:

var regex = /(?:youtu\.be|youtube\.com|ytimg\.com|youtube-nocookie\.com).*(?:\/|\?v=|\&v=|\?video_id=|\&video_id=)([\w\-_]{11})[^\w\-_]?/ig; 

i have embedded youtube iframe looks 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 can see, regex should match against src attribute of element. however, if following code return false:

regex.test( $('#ytplayer').attr('src') ); 

you "well, regex wrong, check again". have @ this:

regex.test( $('#ytplayer').attr('src').tostring() ); 

this return true though exact same code, added tostring(). , yes, .attr('src') returns string! why this? can reproduce in chrome , firefox it's not bug in js implementation.

(you can find jsfiddle try out here)

since using regex testing not use g flag

var regex = /(?:youtu\.be|youtube\.com|ytimg\.com|youtube-nocookie\.com).*(?:\/|\?v=|\&v=|\?video_id=|\&video_id=)([\w\-_]{11})[^\w\-_]?/i; 

when use g flag regex processor remember position of last search , in next search continue there. if there no match in second search again index resetted 0;

demo: fiddle

if want further clarity @ this demo same search repeated 1 after first 1 matches , second 1 fails


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -