Javascript regex split reject null

大憨熊 提交于 2019-12-12 10:46:27

问题


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?


回答1:


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.




回答2:


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

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

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


来源:https://stackoverflow.com/questions/16701319/javascript-regex-split-reject-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!