javascript正则表达式对字符串分组时产生空字符串组?

javascript分割字符串,将汉字和非汉字分割出来,
'张sdf四上法asdf翁芬aa33网s'.split(/([\u4e00-\u9fa5]{1})/gi);
但返回的结果数组里却多出来几个空字符串:
["","张","sdf","四","","上","","法","asdf","翁","","芬","aa33","网","s"]
请问这个空字符串是怎么出来的?应该如何去除?
首页感谢@KevinYue和@皓矾的回答,我的需求其实是把单个汉字分割出来,而且汉字和非汉字的分割要保证顺序,其实我也有其他的方法做,但我真正的问题是:原来的正则表达式为什么会多出几个空字符串?我一直没想明白,所以期望有人能解释一下。
慕婉清6462132
浏览 325回答 2
2回答

手掌心

这样也行吧?不过估计有更简化的写法。我忘了有没有直接前前一个匹配项取反了……"张sdf四上法asdf翁芬aa33网s".match(/([\u4e00-\u9fa5]{1,})|([^\u4e00-\u9fa5]{1,})/gi);//输出["张","sdf","四上法","asdf","翁芬","aa33","网","s"]如果是要每个字符都分开是这样"张sdf四上法asdf翁芬aa33网s".match(/([\u4e00-\u9fa5]{1})|([^\u4e00-\u9fa5]{1,})/gi);//输出["张","sdf","四","上","法","asdf","翁","芬","aa33","网","s"]至于为什么会出现多余的空字符串,其实是String.prototype.split使用正则表达式做为separator造成的,举个最简单的例子:"abc".split(/([a-z])/gi);//输出["","a","","b","","c",""]时间不多,具体String.prototype.split的实现源码还没来得及看,但问题是出在它身上。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript