javascript - 如何删除字符串中由连字符分隔的第一个单词
问题描述
我有一个这样的字符串:
"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
有什么办法可以删除第一个连字符,其余单词必须相同,就像用连字符分开一样
解决方案
您可以改用正则表达式:从字符串的开头匹配直到 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('-')
);
推荐阅读
- ios - 将 CollectionViewCell 移动到另一个部分
- python - Python - 在循环中使用 re-sub 不起作用
- html - 更改 HTML 表格中整行的背景颜色
- excel - 使用 VBA 创建和命名图表
- javascript - Chrome 扩展内容脚本 - 在页面代码之前注入 Javascript
- angular - Angular Router:获取与当前路由匹配的路由配置
- c# - 批量到 FireStore:集合已修改;枚举操作可能无法执行
- git - git diff 将相同的文件显示为不同的文件
- python - 使用 groupby 计算列表中的字符串开关
- python - Python kv文件如何从另一个类调用函数