首页 > 解决方案 > 如何删除字符串中由连字符分隔的第一个单词

问题描述

我有一个这样的字符串:

"DaLogic-newyork-hamilton-amsterdam-hawai-texas-chicago-ill"

我需要像这样删除带有连字符的第一个单词:

"newyork-hamilton-amsterdam-hawai-texas-chicago-ill"

我可以用第一个连字符删除第一个单词,但问题是其他单词变成这样

 ["newyork", "hamilton", "amsterdam", "hawai", "texas", "chicago", "ill"].

这是代码

this.names.split.length>1 ? this.names.split("-").splice(1):this.names

有什么办法可以删除第一个连字符,其余单词必须相同,就像用连字符分开一样

标签: javascriptangular

解决方案


您可以改用正则表达式:从字符串的开头匹配直到 a 的任何内容-,然后替换为空字符串:

const str = "DaLogic-newyork-hamilton-amsterdam-hawai-texas-chicago-ill";
console.log(
  str.replace(
    /.*?-/,
    ''
  )
);

您也可以按 拆分-,然后移出第一项(DaLogic部分),然后加入:

const str = "DaLogic-newyork-hamilton-amsterdam-hawai-texas-chicago-ill";
const arr = str.split('-');
arr.shift();
console.log(
  arr.join('-')
);


推荐阅读