Javascript regex split reject null

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

Can String.split () method reject null values?

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

-

While I tested this, I came across a partial answer to the case:

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

But the problem occurs when the match is at the beginning:

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

Is there a clean answer? Or do we just need to deal with this?

+5
javascript null split regex
May 22 '13 at 20:47
source share
2 answers

This is not a very regular solution, but the filter will quickly execute it.

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

This will filter out false "" values.

+22
May 22 '13 at 20:50
source share

Trim matches from line ends before splitting:

 console.log("abccacaab".replace(/^a+|a+$/g, '').split(/a+/)); // ["bcc", "c", "b"] 
+1
May 22 '13 at 20:52
source share



All Articles