JavaScript string split by Regex results sub-strings include empty slices

南笙酒味 提交于 2019-12-20 06:26:09

问题


I've the following string splitting JavaScript code:

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.split(/[+(-)% *\/]/));

And the result is out of expectation:

["", "field1", "", "", "field2", "", "", "", "", "field5", "", "", "field2", "", "", "", "field3"]

What the desired result would be:

["field1", "field2", "field5", "field2", "field3"]

I'm using Google Chrome 11 official release as the testing browser, please kindly advise what I'm doing wrong.

Thank you!

William


回答1:


Instead of splitting on /[+(-)% *\/]/ split on more than one: /[+(-)% *\/]+/. You still might get empty matches at the start and end. To solve that problem you can use a similar regex with replace:

formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/)

So

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/));

yields

field1,field2,field5,field2,field3



回答2:


You are splitting at each of those characters. If you split on groups of them, you'll get your desired result.

console.log(formula.split(/[+(-)% *\/]+/));

There's just one snag: you will have to manually strip off those characters from the beginning and the end of the string (or pop off an empty string at the start/end) - it's not something you'll be able to handle by split alone.



来源:https://stackoverflow.com/questions/6105067/javascript-string-split-by-regex-results-sub-strings-include-empty-slices

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