如何在Fle扩展之前删除文本

时间:2019-03-05 08:06:28

标签: javascript

我想在图像的文件扩展名之前删除3个字符,例如图像的此路径。

来自此<img src="www.example.com/img/image123.jpg"> 对此<img src="www.example.com/img/image.jpg">

如何在javascript中做到这一点?

1 个答案:

答案 0 :(得分:1)

由于您不够具体,我这样做了:

// Your array of files
const files = [ 'image123.jpg', 'test.jpg', 'file.txt', 'docum123ents.doc' ];
// The part you want to remove from each file you are going to scan
const partToRemove = '123';
// New array with new files name
let newFiles = [];

console.log(files);

// For each file in files
newFiles = files.map(element => {
    // if element includes the part you want to remove
    if (element.includes(partToRemove)) {
        // replace that part with an empty string and return the element
        return element.replace(partToRemove, '');
    } else {
        // return the element, it's already without 'partToRemove'
        return element;
    }
});

console.log('------');
console.log(newFiles);

输出:

[ 'image123.jpg', 'test.jpg', 'file.txt', 'docum123ents.doc' ]
------
[ 'image.jpg', 'test.jpg', 'file.txt', 'documents.doc' ]