我正在尝试使用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 ;
答案 0 :(得分:3)
分割,切片和合并
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);
没有地图:
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);
答案 1 :(得分:1)
使用正则表达式从字符串开头匹配非数字字符,后跟-
和一个数字:
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const output = input.map(str => str.match(/\D+(?=-\d)/)[0]);
console.log(output);
答案 2 :(得分:0)
使用split on -
,将最后一个元素(即日期和joining on -
)相切
var arr=["power-still-rate-19.08.22","main-still-rate-19.08.22","oil-power-rate-19.08.22"];
arr.forEach(function(e,i){
arr[i]=e.split('-').splice(0,3).join('-')
})
console.log(arr)
答案 3 :(得分:0)
您可以使用String#replace
方法来使用RegExp从字符串中删除某些模式。
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const res = input.map(str => str.replace(/-\d{1,2}\.\d{1,2}\.\d{1,2}$/, ''));
console.log(res);
答案 4 :(得分:0)
您可以使用slice
函数删除后退字符串,并使用join
函数将它们加入。
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(str => str.slice(0, str.lastIndexOf('-'))).join(',');
console.log(result);