Dinesh
Dinesh

Reputation: 4559

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)

Upvotes: 1

Views: 55

Answers (2)

user557597
user557597

Reputation:

Moved from comment (per request).

Try to split on /_(?=[1-3]$)/

Upvotes: 1

whatoncewaslost
whatoncewaslost

Reputation: 2256

Use .match instead.

"abc_d_3".match(re)

That should return this:

["abc_d_3", "abc_d", "3"]

Upvotes: 1

Related Questions