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

后端 未结 2 701
悲哀的现实
悲哀的现实 2021-01-26 09:26

I\'ve the following string splitting JavaScript code:

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


        
相关标签:
2条回答
  • 2021-01-26 09:52

    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
    
    0 讨论(0)
  • 2021-01-26 09:54

    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.

    0 讨论(0)
提交回复
热议问题