目标:我想用破折号分割字符串,其中每个数组项都排除任何空格。

例:

字符串->“ CL-目的地-机场税”

我试过了 :

var splitArray = section.split(/[-]+/);


预期:

splitAray [0] = "CN"
splitAray [1] = "Transit "
splitAray [2] = "Airport Tax"


实际:

splitAray [0] = "CN "
splitAray [1] = " Transit "
splitAray [2] = " Airport Tax"


如何轻松去除任何外部空间?

最佳答案

maptrim一起使用:



const section = "CL - Destination - Airport Tax";
const splitArray = section.split(/[-]+/).map(s => s.trim());
console.log(splitArray);





ES5语法:



var section = "CL - Destination - Airport Tax";
var splitArray = section.split(/[-]+/).map(function(s) {
  return s.trim();
});
console.log(splitArray);

09-15 13:29