【问题标题】:How to split a string by dashes and removing any outer white space?如何用破折号分割字符串并删除任何外部空格?
【发布时间】:2019-04-25 04:49:00
【问题描述】:
目标:我想用破折号分割一个字符串,其中每个数组项不包括任何空格。
例子:
string --> "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"
如何轻松删除任何外部空间?
【问题讨论】:
标签:
javascript
arrays
regex
string
【解决方案1】:
将map 与trim 一起使用:
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);
【解决方案2】:
只需在破折号的两侧添加可选的空格:
var section = "CL - Destination - Airport Tax";
var splitArray = section.split(/\s*[-]\s*/);
console.log(splitArray);
【解决方案3】:
这里是解映射函数会自动修剪数组的每个元素。
var section ="CL - Destination - Airport Tax";
var splitArray =section.split('-').map(Function.prototype.call, String.prototype.trim);