javascript - 如何在文件扩展之前删除文本
问题描述
我想在图像的文件扩展名之前删除 3 个字符,例如这个图像路径。
从这个<img src="www.example.com/img/image123.jpg">
到这个<img src="www.example.com/img/image.jpg">
如何在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' ]
推荐阅读
- python - IPython 检测自动魔法
- javascript - 如何将字符串值从对象转换为数字和布尔值?
- sql - 我在这个查询中遇到了多个 AND/OR 条件。我是关闭还是有更简单的解决方案?
- google-apps-script - 如何使用 Apps 脚本在工作表侧边栏中发送通知(在新表单提交时)
- android - 设计 - 使用 com.github.mikephil.charting
- vue.js - vue 的 vue-dat-gui 不适用于“无法读取未定义的属性 '_c'”错误消息
- npm - 如何解决 npm install 的错误代码 1
- javascript - Chrome.storage.sync.get 在另一个 .js 文件中
- flutter - Flutter 中的 const 构造函数和 const 对象
- javascript - 在多个画布的 p5js 实例模式下,未定义 p5 对象