Javascript 拆分删除 “:” 冒号字符

Javascript split remove ":" colon character

本文关键字:字符 拆分 删除 Javascript      更新时间:2023-09-26

我有这样的字符串。

var a="1:2:3:";

我想用a.split(":")拆分它以删除":"冒号字符。

我想得到这个结果:

["1","2","3"]

但相反,a.split(":")的结果是这样的:

["1","2","3",""]

使用此修剪方法删除尾随冒号。

function TrimColon(text)
{
    return text.toString().replace(/^(.*?):*$/, '$1');
}

然后你可以这样称呼它:

TrimColon(a).split(":")

如果你愿意,你当然可以TrimColon一个字符串原型方法,允许你做这样的事情:

a.TrimColon().split(":");
如果您想

解释所使用的正则表达式:转到此处

在解析此类字符串之前,您应该从字符串的开头和结尾去除冒号:

a.replace(/(^:)|(:$)/g, '').split(":")

如果您不想像其他答案那样使用正则表达式来执行此操作,则可以选择下面的一个并使用它。

仅删除空字符串

["1","2","3",""].filter(String)
// ['1', '2', '3']
["1","2","3","", 123].filter(String)
// ['1', '2', '3', 123]
["1","2","3","", 123, null, undefined].filter(String)
// ['1', '2', '3', 123, null, undefined]
// Function
function RemoveEmptyString(arr) {
  if (Array.isArray(arr))
    return arr.filter(String);
  else
    return [];
}
RemoveEmptyString(["1","2","3",""])
// ["1","2","3"];
// Prototype
Object.defineProperty(Array.prototype, 'removeEmptyStrings', {
  value: function () {
    return this.filter(String);
  }
});
["1","2","3", ""].removeEmptyStrings()
// ["1","2","3"]

仅删除无效元素

["1","2","3",""].filter(Value => Value)
// ['1', '2', '3']
["1","2","3","", 123].filter(Value => Value)
// ['1', '2', '3', 123]
["1","2","3","", 123, null, undefined].filter(Value => Value)
// ['1', '2', '3', 123]
// Function
function RemoveEmptyString(arr) {
  if (Array.isArray(arr))
    return arr.filter(Value => Value);
  else
    return [];
}
RemoveEmptyString(["1","2","3","", 123, null, undefined])
// ["1","2","3", 123]
// Prototype
Object.defineProperty(Array.prototype, 'removeEmptyStrings', {
  value: function () {
    return this.filter(Value => Value);
  }
});
["1","2","3","", 123, null, undefined].removeEmptyStrings()
// ["1","2","3", 123]