精品学习网->精美文摘

上一篇    全部文章
js去掉文件后缀名

js去掉文件后缀名


以下是不同的实现方法,但都能去掉 JavaScript 文件的后缀名:

方法一:使用正则表达式

const filename = "file.js";
const noExtension = filename.replace(/\.[^/.]+$/, ""); // 输出 "file"
 
// 如果需要删除路径中的文件后缀名,可以使用以下代码:
const filepath = "/path/to/file.js";
const noExtension = filepath.replace(/(.*)\.[^.]+$/, "$1"); // 输出 "/path/to/file"
方法二:使用字符串截取

const filename = "file.js";
const noExtension = filename.slice(0, filename.lastIndexOf(".")); // 输出 "file"
 
// 如果需要删除路径中的文件后缀名,可以使用以下代码:
const filepath = "/path/to/file.js";
const noExtension = filepath.slice(0, filepath.lastIndexOf(".")); // 输出 "/path/to/file"
方法三:使用路径处理模块(如Node.js中的path模块)

const path = require("path");
 
const filename = "file.js";
const noExtension = path.parse(filename).name; // 输出 "file"
 
// 如果需要删除路径中的文件后缀名,可以使用以下代码:
const filepath = "/path/to/file.js";
const noExtension = path.parse(filepath).dir; // 输出 "/path/to/file"
这些方法都能有效地去掉 JavaScript 文件的后缀名,并适用于不同的场景。选择使用哪种方法取决于个人偏好和项目要求。

 



     返回顶部
js去掉文件后缀名