Javascript正则表达式拆分拒绝null [英] Javascript regex split reject null
本文介绍了Javascript正则表达式拆分拒绝null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使JavaScript正则表达式拒绝空匹配?
Is it possible to make a JavaScript regex reject null matches?
可以告诉String.split()方法拒绝空值吗?
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"]
// ^^
有一个干净的答案吗?或者我们只需要处理它?</ p>
Is there a clean answer? Or do we just have to deal with it?
推荐答案
这不是一个正则表达式解决方案,但过滤器会快速它的工作。
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.
这篇关于Javascript正则表达式拆分拒绝null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文