首页 > 解决方案 > 如何在文件扩展之前删除文本

问题描述

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

从这个<img src="www.example.com/img/image123.jpg"> 到这个<img src="www.example.com/img/image.jpg">

如何在javascript中做到这一点?

标签: javascript

解决方案


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

// 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' ]

推荐阅读