Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex split reject null

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?

like image 819
Isaac Avatar asked May 22 '13 20:05

Isaac


1 Answers

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.

like image 173
user1106925 Avatar answered Oct 21 '22 03:10

user1106925