如何从 JavaScript 中的字符串修剪文件扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4250364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:35:15  来源:igfitidea点击:

How to trim a file extension from a String in JavaScript?

javascriptreplacesubstringsubstrindexof

提问by ma11hew28

For example, assuming that x = filename.jpg, I want to get filename, where filenamecould be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).

例如,假设x = filename.jpg,我想得到filename,其中filename可以是任何文件名(假设文件名仅包含 [a-zA-Z0-9-_] 以简化。)。

I saw x.substring(0, x.indexOf('.jpg'))on DZone Snippets, but wouldn't x.substring(0, x.length-4)perform better? Because, lengthis a property and doesn't do character checking whereas indexOf()is a function and does character checking.

x.substring(0, x.indexOf('.jpg'))DZone Snippets上看到过,但不会x.substring(0, x.length-4)表现得更好吗?因为,length是一个属性,不做字符检查,而indexOf()是一个函数,做字符检查。

采纳答案by Marek Sapota

If you know the length of the extension, you can use x.slice(0, -4)(where 4 is the three characters of the extension and the dot).

如果您知道扩展名的长度,则可以使用x.slice(0, -4)(其中 4 是扩展名和点的三个字符)。

If you don't know the length @John Hartsock regex would be the right approach.

如果您不知道长度 @John Hartsock regex 将是正确的方法。

If you'd rather not use regular expressions, you can try this (less performant):

如果你不想使用正则表达式,你可以试试这个(性能较差):

filename.split('.').slice(0, -1).join('.')

Note that it will fail on files without extension.

请注意,它会在没有扩展名的文件上失败。

回答by John Hartsock

Not sure what would perform faster but this would be more reliable when it comes to extension like .jpegor .html

不确定什么会执行得更快,但这在扩展时会更可靠,例如.jpeg.html

x.replace(/\.[^/.]+$/, "")

回答by Jibesh Patra

In node.js, the name of the file without the extension can be obtained as follows.

node.js 中,可以通过如下方式获取不带扩展名的文件名。

const path = require('path');
const filename = 'hello.html';

path.parse(filename).name; // hello
path.parse(filename).ext;  // .html

Further explanation at Node.jsdocumentationpage.

Node.js文档页面进一步解释。

回答by Jeff B

x.length-4only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?

x.length-4仅占 3 个字符的扩展名。如果你有filename.jpegfilename.pl怎么办?

EDIT:

编辑:

To answer... sure, if you always have an extension of .jpg, x.length-4would work just fine.

要回答......当然,如果你总是有一个扩展.jpgx.length-4会工作得很好。

However, if you don't know the length of your extension, any of a number of solutions are better/more robust.

但是,如果您不知道扩展的长度,那么许多解决方案中的任何一个都更好/更健壮。

x = x.replace(/\..+$/, '');

x = x.replace(/\..+$/, '');

OR

或者

x = x.substring(0, x.lastIndexOf('.'));

x = x.substring(0, x.lastIndexOf('.'));

OR

或者

x = x.replace(/(.*)\.(.*?)$/, "$1");

x = x.replace(/(.*)\.(.*?)$/, "$1");

OR (with the assumption filename only has one dot)

或(假设文件名只有一个点)

parts = x.match(/[^\.]+/);
x = parts[0];

OR (also with only one dot)

或(也只有一个点)

parts = x.split(".");
x = parts[0];

回答by Martin Algesten

You can perhaps use the assumption that the last dot will be the extension delimiter.

您也许可以假设最后一个点将是扩展分隔符。

var x = 'filename.jpg';
var f = x.substr(0, x.lastIndexOf('.'));

If file has no extension, it will return empty string. To fix that use this function

如果文件没有扩展名,它将返回空字符串。要解决该问题,请使用此功能

function removeExtension(filename){
    var lastDotPosition = filename.lastIndexOf(".");
    if (lastDotPosition === -1) return filename;
    else return filename.substr(0, lastDotPosition);
}

回答by jakubiszon

I like this one because it is a one liner which isn't too hard to read:

我喜欢这个,因为它是一种不太难阅读的单线:

filename.substring(0, filename.lastIndexOf('.')) || filename

回答by blah238

In Node.js versions prior to 0.12.x:

在 0.12.x 之前的 Node.js 版本中:

path.basename(filename, path.extname(filename))

path.basename(filename, path.extname(filename))

Of course this also works in 0.12.x and later.

当然,这也适用于 0.12.x 及更高版本。

回答by Andrew Plank

This works, even when the delimiter is not present in the string.

即使字符串中不存在分隔符,这也有效。

String.prototype.beforeLastIndex = function (delimiter) {
    return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
}

"image".beforeLastIndex(".") // "image"
"image.jpeg".beforeLastIndex(".") // "image"
"image.second.jpeg".beforeLastIndex(".") // "image.second"
"image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"

Can also be used as a one-liner like this:

也可以像这样用作单线:

var filename = "this.is.a.filename.txt";
console.log(filename.split(".").slice(0,-1).join(".") || filename + "");

EDIT: This is a more efficient solution:

编辑:这是一个更有效的解决方案:

String.prototype.beforeLastIndex = function (delimiter) {
    return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
}

回答by Giacomo Cerquone

I don't know if it's a valid option but I use this:

我不知道这是否是一个有效的选项,但我使用这个:

name = filename.split(".");
// trimming with pop()
name.pop();
// getting the name with join()
name.join('.'); // we split by '.' and we join by '.' to restore other eventual points.

It's not just one operation I know, but at least it should always work!

这不仅仅是我知道的一种操作,但至少它应该始终有效!

UPDATE: If you want a oneliner, here you are:

更新:如果你想要一个oneliner,你在这里:

(name.split('.').slice(0, -1)).join('.')

(name.split('.').slice(0, -1)).join('.')

回答by Chad Johnson

Here's another regex-based solution:

这是另一个基于正则表达式的解决方案:

filename.replace(/\.[^.$]+$/, '');

This should only chop off the last segment.

这应该只切断最后一段。