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?

Isaac
  • 11,409
  • 5
  • 33
  • 45

2 Answers2

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.

  • I feel like I've been stealing all your rep! http://stackoverflow.com/questions/19888689/remove-empty-strings-from-array-while-keeping-record-without-loop/19888749#19888749 – Isaac Aug 01 '16 at 22:02
  • @Isaac: LOL, nah I make my answers into CW's anyway. Glad to see you use the info! –  Aug 02 '16 at 00:40
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"]
Paul
  • 139,544
  • 27
  • 275
  • 264
  • That's nice, not as clean as squint's answer though – Isaac May 22 '13 at 20:55
  • @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. – Paul May 22 '13 at 21:08