1
// 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)

3
  • @sln if you write that up, I can accept that as most concise answer (apologies OceansOnPluto :-( Commented Jul 2, 2015 at 1:41
  • Moved comment to answer. Commented Jul 2, 2015 at 2:16
  • Not sure why you escape ( and ). Although the string ends up being the same as "^(.*)_([1-3])$", it's better if you don't escape them at all "^(.*)_([1-3])$". Anyway, it's better to use RegExp literal instead of calling RegExp constructor when you have a fixed pattern. Commented Jul 2, 2015 at 3:34

2 Answers 2

1

Moved from comment (per request).

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use .match instead.

"abc_d_3".match(re)

That should return this:

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

1 Comment

I also liked the comment by @sln, and am actually going to use that. It is more concise and the code describes exactly what I am trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.