javascript - Why does string.match(...)[0] throws an exception? -
i'm trying pull first occurence of regex pattern string in 1 statement create code cleaner. want do:
var matchedstring = somestring.match(/some regex/g)[0]; i expect legal throws exception:
exception: somestring.match(...) null it seems js trying index array before match finsihed, array provide atleast 1 match, don't expect null.
i insight in why happens. bug?
my machine pc running arch linux x86_64. code beingness executed within scratchpad of firefox 32.0.3.
thanks interest.
if somestring.match() finds no match, returns null.
and, null[0] throws exception.
since getting exact exception, regex not beingness found in content. careful using g flag on match alternative in way not expect when have submatches specified in regex. since looks want first match anyway, should remove g option.
a safer way code is:
var matches = somestring.match(/some regex/); if (matches) { // here matches[0] } javascript regex string match
No comments:
Post a Comment