在JavaScript中获取文件名而不带后缀可以通过多种方式实现。以下是一个简单的方法:
.
)之后的部分,通常用来表示文件的格式。以下是一个JavaScript函数,用于从完整的文件路径中提取不带后缀的文件名:
function getFileNameWithoutExtension(filePath) {
// 使用lastIndexOf找到最后一个点的位置
var lastDotIndex = filePath.lastIndexOf('.');
// 如果没有点,或者点在字符串的最开始位置,则整个字符串都是文件名
if (lastDotIndex === -1 || lastDotIndex === 0) {
return filePath;
}
// 返回从开始到最后一个点之前的子字符串
return filePath.substring(0, lastDotIndex);
}
// 使用示例
var fileName = getFileNameWithoutExtension('path/to/myfile.txt');
console.log(fileName); // 输出: myfile
function getFileNameWithoutExtension(filePath) {
// 使用正则表达式匹配最后一个点及其之后的内容,并将其替换为空字符串
return filePath.replace(/\.[^.]+$/, '');
}
// 使用示例
var fileName = getFileNameWithoutExtension('path/to/my.file.with.multiple.dots.txt');
console.log(fileName); // 输出: my.file.with.multiple.dots
这种方法可以正确处理包含多个点的复杂文件名。
通过以上方法,你可以有效地从文件路径中提取出不带后缀的文件名,适用于各种前端开发场景。
领取专属 10元无门槛券
手把手带您无忧上云