如何从 JavaScript 中的字符串修剪文件扩展名? [英] How to trim a file extension from a String in JavaScript?

查看:43
本文介绍了如何从 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'))rel="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 regex 将是正确的方法.

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 中的字符串修剪文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆