我要在其中添加一些后缀的数组值:
var arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
添加前缀'_ thumb'应该会导致以下结果:
newArr = ["folder1/1_thumb.jpg","folder2/2_thumb.png","foldern/some_thumb.jpg"];
这是我的代码,但是不好:
var arr = ["folder1/1.jpg", "folder2/2.png", "foldern/some.jpg"];
var newArr = [];
arr.forEach(image => {
var onlyPath = path.dirname(image);
var filename = path.basename(image).split('.');
newArr.push(onlyPath + '/' + filename[0] + '_thumb' + '.' + filename[1]);
});
console.log(newArr);
答案 0 :(得分:3)
使用此:
var arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
var newArr = [];
arr.forEach(filename => {
var name = filename.split('.').slice(0, -1).join('.')+'_thumb.'+filename.split('.').pop();
newArr.push(name);
console.log('name ',name );
});
答案 1 :(得分:1)
您可以使用Array.map
let arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
let newArr = arr.map(img => img.split('.').join('_thumb.'));
console.log(newArr)
答案 2 :(得分:1)
如果您在数组中具有不同的扩展名(例如.png,.jpeg等),则此选项非常适用
var arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
for (var i = 0; i < arr.length; i++) {
var splitted_string = arr[i].split(".");
arr[i] = splitted_string[0]+"_thumb."+splitted_string[1];
console.log(arr[i]);
}
答案 3 :(得分:1)
尝试:
arr.map(function(el) {
return el.replace(/\./g,"_thumb.")
})
答案 4 :(得分:1)
使用split()。这很简单。 ew;)
let arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
let newArr = arr.map(img => img.split('.')[0] + '_thumb.' + img.split('.')[1]);
console.log(newArr)
答案 5 :(得分:0)
下面给出的代码可以为您提供帮助。它会在扩展名“ .xxx”之前插入给定的(_thumb)字符串
//function to run
function test()
{
var arr = ["folder1/1.jpg","folder2/2.png","foldern/some.jpg"];
var newArr=[];
for(i in arr)
{
//gets the index of "." sign to add the "_thumb" string before it
var pos=arr[i].indexOf(".");
var newVal=insert(arr[i], pos, "_thumb");
newArr.push(newVal);
}
}
//inserts the given string ("_thumb") between the array value
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}