6

Is it possible to make a JavaScript regex reject null matches?

Can the String.split() method be told to reject null values?

console.log("abcccab".split("c"));
//result: ["ab", "", "", "ab"]
//desired result: ["ab", "ab"]

-

While I was testing this I came across a partial answer on accident:

console.log("abccacaab".split(/c+/));
//returns: ["ab", "a", "aab"] 

But, a problem arises when the match is at the start:

console.log("abccacaab".split(/a+/));
//returns: ["", "bcc", "c", "b"]
//          ^^

Is there a clean answer? Or do we just have to deal with it?

2
  • How about matching all sequences of characters except c? Commented May 22, 2013 at 20:49
  • @nathanhayfield That's what I'm wanting to avoid Commented May 22, 2013 at 20:50

2 Answers 2

29

This isn't precisely a regex solution, but a filter would make quick work of it.

"abcccab".split("c").filter(Boolean);

This will filter out the falsey "" values.

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

2 Comments

I feel like I've been stealing all your rep! stackoverflow.com/questions/19888689/…
@Isaac: LOL, nah I make my answers into CW's anyway. Glad to see you use the info!
1

Trim the matches from the ends of the string before you split:

console.log("abccacaab".replace(/^a+|a+$/g, '').split(/a+/));

// ["bcc", "c", "b"]

2 Comments

That's nice, not as clean as squint's answer though
@Nope, I left it here because you told nathanhayfield that you wanted to avoiding iterating through the array and removing the empty strings, which is what filter does.

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.