mercredi 1 juillet 2015

String split with RegExp returns empty strings at either end

// pattern -- <some name with an optional 1/2/3 at end separated by a _>
var re = new RegExp("^\(.*\)_\([1-3]\)$")
"".split(re) 
// returns [""] --- OK
"abc_d_4".split(re) 
// returns ["abc_d_4"] --- OK
"abc_d_3".split(re)
// returns ["", "abc_d", "3", ""] --- WHOA! hoped-for was ["abc_d", "3"]
// similarly, "_3".split(re), "abc_d_3_4_3".split(re)

why the extra empty strings at either end in the last case, and how to avoid that? I would definitely appreciate an explanation.

I can see similar questions have been asked before on SO but not this case (or pl point me there)

Aucun commentaire:

Enregistrer un commentaire