如何在JavaScript中修剪String中的文件扩展名? [英] How to trim a file extension from a String in JavaScript?
问题描述
例如,假设 x = filename.jpg
,我想得到 filename
,其中 filename
可以是任何文件名(假设文件名只包含[a-zA-Z0-9-_]以简化。)。
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.).
我在 x.substring(0,x.indexOf('。jpg'))。 com / posts / show / 4060rel =noreferrer> DZone Snippets ,但不会 x.substring(0,x.length-4)
表现更好?因为, length
是一个属性,不进行字符检查,而 indexOf()
是一个函数并进行字符检查。
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.
推荐答案
如果您知道扩展名的长度,可以使用 x.slice(0, -4)
(其中4是扩展名和点的三个字符)。
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).
如果你不知道@John的长度Hartsock正则表达式将是正确的方法。
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):
filename.split('.').slice(0, -1).join('.')
请注意,没有扩展名的文件会失败。
Note that it will fail on files without extension.
这篇关于如何在JavaScript中修剪String中的文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!