gpt4 book ai didi

javascript - 如何使用 javascript 从字符串中获取特定文本

转载 作者:行者123 更新时间:2023-11-28 14:15:39 24 4
gpt4 key购买 nike

我正在尝试使用 javascript 从数组中获取除年、月、日期之外的文本。我不知道该怎么做。

var arr = [
"power-still-rate-19.08.22",
"main-still-rate-19.08.22",
"oil-power-rate-19.08.22",
"oil-mill-rate-19.7.2"
];
var result;

for (var i = 0; i < arr.length; i++) {
result = arr[i].remove('?????????');
}
console.log(result);

//result should be like = power-still-rate,main-still-rate,oil-power-rate ;

最佳答案

分割、切片和连接

var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => item.split("-").slice(0,-1).join("-"))
console.log(result);

拆分、弹出和合并

var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => { let res = item.split("-"); res.pop(); return res.join("-") })
console.log(result);

没有 map :

var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.join("").split(/-\d{1,}\.\d{1,}\.\d{1,}/);
result.pop(); // last empty item, not needed if you do not want an array just join with comma
console.log(result);

关于javascript - 如何使用 javascript 从字符串中获取特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com