如何在 JavaScript 中从字符串中删除文件扩展名?
例如,假设x = filename.jpg
,我想获取filename
,其中filename
可以是任何文件名(让我们假设文件名称仅包含 [a-zA-Z0-9-_] 以简化。)。
我在 DZone Snippets,但是 x.substring(0, x.length-4)
性能不是更好吗?因为,length
是一个属性,不执行字符检查,而 indexOf()
是一个函数,执行字符检查。
For example, assuming that x = filename.jpg
, I want to get filename
, where filename
could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).
I saw x.substring(0, x.indexOf('.jpg'))
on DZone Snippets, but wouldn't x.substring(0, x.length-4)
perform better? Because, length
is a property and doesn't do character checking whereas indexOf()
is a function and does character checking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
不确定什么会执行得更快,但是当涉及
.jpeg
或.html
等扩展时,这会更可靠Not sure what would perform faster but this would be more reliable when it comes to extension like
.jpeg
or.html
在node.js中,可以通过以下方式获取不带扩展名的文件名。
更多说明请参见 Node.js 文档 页面。
In node.js, the name of the file without the extension can be obtained as follows.
Further explanation at Node.js documentation page.
如果您知道扩展名的长度,则可以使用 x.slice(0, -4)(其中 4 是扩展名和点的三个字符)。
如果您不知道长度 @John Hartsock 正则表达式 将是正确的方法。
如果您不想使用正则表达式,可以尝试此操作(性能较低):
请注意,它对于没有扩展名的文件将失败。
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).If you don't know the length @John Hartsock regex would be the right approach.
If you'd rather not use regular expressions, you can try this (less performant):
Note that it will fail on files without extension.
x.length-4
仅考虑 3 个字符的扩展名。如果您有filename.jpeg
或filename.pl
怎么办?编辑:
要回答......当然,如果您总是有
.jpg
的扩展名,x.length-4
就可以正常工作。但是,如果您不知道扩展的长度,则许多解决方案中的任何一个都更好/更可靠。
x = x.replace(/\..+$/, '');
或
x = x.substring(0, x.lastIndexOf('.'));
>OR
x = x.replace(/(.*)\.(.*?)$/, "$1");
OR (假设文件名只有一个点)
OR (也可以只有一个点)
x.length-4
only accounts for extensions of 3 characters. What if you havefilename.jpeg
orfilename.pl
?EDIT:
To answer... sure, if you always have an extension of
.jpg
,x.length-4
would work just fine.However, if you don't know the length of your extension, any of a number of solutions are better/more robust.
x = x.replace(/\..+$/, '');
OR
x = x.substring(0, x.lastIndexOf('.'));
OR
x = x.replace(/(.*)\.(.*?)$/, "$1");
OR (with the assumption filename only has one dot)
OR (also with only one dot)
我喜欢这一本,因为它是一本单行本,读起来并不太难:
I like this one because it is a one liner which isn't too hard to read:
您也许可以假设最后一个点将是扩展分隔符。
如果文件没有扩展名,它将返回空字符串。要解决这个问题,请使用此功能
You can perhaps use the assumption that the last dot will be the extension delimiter.
If file has no extension, it will return empty string. To fix that use this function
在 0.12.x 之前的 Node.js 版本中:
path.basename(filename, path.extname(filename))
当然,这也适用于 0.12.x 及更高版本。
In Node.js versions prior to 0.12.x:
path.basename(filename, path.extname(filename))
Of course this also works in 0.12.x and later.
我不知道这是否是一个有效的选项,但我使用这个:
这不仅仅是我知道的一项操作,但至少它应该始终有效!
更新:如果你想要一个oneliner,这里是:
(name.split('.').slice(0, -1)).join('.')
I don't know if it's a valid option but I use this:
It's not just one operation I know, but at least it should always work!
UPDATE: If you want a oneliner, here you are:
(name.split('.').slice(0, -1)).join('.')
即使字符串中不存在分隔符,这种方法也有效。
也可以用作这样的单行:
编辑:这是一种更有效的解决方案:
This works, even when the delimiter is not present in the string.
Can also be used as a one-liner like this:
EDIT: This is a more efficient solution:
另一句:
Another one-liner:
如果您必须处理包含完整路径的变量(例如:
thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg"
)并且您只想返回“ filename" 你可以使用:结果将是 theName == "filename";
要尝试将以下命令写入 chrome 调试器的控制台窗口:
window.location.pathname.split("/").slice(-1).join().split(".").shift()
如果您有仅处理文件名及其扩展名(例如:
theNameWithExt = "filename.jpg"
):结果将是theName == "filename",与多于;
注意:
运营;但在两种情况下都有效,换句话说它可以提取
不带扩展名的文件名,来自包含路径或带有 ex 的文件名的给定字符串。而第二个仅当给定变量包含带有 ext 的文件名(如 filename.ext)时才有效,但速度要快一些。
但我不能说与其他答案的性能比较,也不能说浏览器或操作系统兼容性。
工作片段 1:完整路径
工作片段 2:带扩展名的文件名
工作片段 2:具有双扩展名的文件名
If you have to process a variable that contains the complete path (ex.:
thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg"
) and you want to return just "filename" you can use:the result will be theName == "filename";
To try it write the following command into the console window of your chrome debugger:
window.location.pathname.split("/").slice(-1).join().split(".").shift()
If you have to process just the file name and its extension (ex.:
theNameWithExt = "filename.jpg"
):the result will be theName == "filename", the same as above;
Notes:
operations; but works in both cases, in other words it can extract
the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.
But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.
working snippet 1: the complete path
working snippet 2: the file name with extension
working snippet 2: the file name with double extension
这是另一个基于正则表达式的解决方案:
这应该只截断最后一段。
Here's another regex-based solution:
This should only chop off the last segment.
简单的一个:
Simple one:
接受的答案仅删除最后一个扩展部分(
.jpeg
),这在大多数情况下可能是一个不错的选择。我曾经不得不删除所有扩展名 (
.tar.gz
),并且文件名被限制为不包含点(因此2015-01-01.backup.tar
不会是一个问题):The accepted answer strips the last extension part only (
.jpeg
), which might be a good choice in most cases.I once had to strip all extensions (
.tar.gz
) and the file names were restricted to not contain dots (so2015-01-01.backup.tar
would not be a problem):例子:
Example:
Node.js 从完整路径保留目录中删除扩展
https://stackoverflow.com/a/31615711/895245 例如,
path/hello.html
->hello
,但如果你想要path/hello.html
->path/hello
,您也可以使用以下输出目录:
https://stackoverflow.com/a /36099196/895245 也实现了这一点,但我发现这种方法在语义上更令人愉悦。
在 Node.js v10.15.2 中测试。
Node.js remove extension from full path keeping directory
https://stackoverflow.com/a/31615711/895245 for example did
path/hello.html
->hello
, but if you wantpath/hello.html
->path/hello
, you can use this:outputs directory as well:
https://stackoverflow.com/a/36099196/895245 also achieves this, but I find this approach a bit more semantically pleasing.
Tested in Node.js v10.15.2.
虽然已经很晚了,但我将添加另一种方法来使用普通的旧 JS 获取不带扩展名的文件名
-
path.replace(path.substr(path.lastIndexOf('.')), '')
Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-
path.replace(path.substr(path.lastIndexOf('.')), '')
我们可能会遇到带有多个扩展名后缀的文件名或文件路径。请考虑以下事项来修剪它们。
输出结果:“/dir/path/filename”
它解决了文件扩展名问题,特别是当输入有多个扩展名时。
We might come across filename or file path with multiple extension suffix. Consider the following to trim them.
result of output: "/dir/path/filename"
It solves the file extension problem especially when the input has multiple extensions.
这可能会有所帮助...
This might help...
这就是正则表达式派上用场的地方! Javascript 的
.replace()
方法将采用正则表达式,您可以利用它来完成您想要的操作:This is where regular expressions come in handy! Javascript's
.replace()
method will take a regular expression, and you can utilize that to accomplish what you want:您可以使用
path
来操纵。输出
You can use
path
to maneuver.Output
这是我用来从文件名中删除扩展名的代码,无需使用正则表达式或indexOf(IE8 不支持indexOf)。它假定扩展名是最后一个“.”之后的任何文本。特点。
它适用于:
以下是代码:
This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.
It works for:
Here's the code:
我喜欢使用正则表达式来做到这一点。它简短且易于理解。
上面的解释可能不是很严谨。如果想得到更准确的解释可以去regex101查看
I like to use the regex to do that. It's short and easy to understand.
The above explanation may not be very rigorous. If you want to get a more accurate explanation can go to regex101 to check
在节点中:
或者如果您想确保删除特定扩展名(但仅当存在时)
为什么上述:
例如
In node:
or if you want to make sure that you remove a specific extension (but only if present)
why the above:
e.g.
另一张衬垫 - 我们假设我们的文件是一张 jpg 图片>>>例如:var yourStr = 'test.jpg';
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
试试这个
.split('.')[0]
它对我有用
Try this one
.split('.')[0]
it worked for me
这就是全部享受你的编码......
that's all enjoy your coding...
我会使用类似 x.substring(0, x.lastIndexOf('.')) 的东西。如果你追求性能,根本就不要选择 javascript :-p 不,多一条语句对于 99.99999% 的所有目的来说确实无关紧要。
I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.