【问题标题】: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】:

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);

【讨论】:

    【解决方案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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-15
        • 1970-01-01
        • 2016-12-17
        • 2011-08-17
        • 2016-12-21
        • 2012-01-02
        • 2021-04-03
        • 2023-03-20
        相关资源
        最近更新 更多