如何在 JavaScript 中从字符串中删除文件扩展名?

发布于 2024-10-04 00:57:17 字数 412 浏览 1 评论 0原文

例如,假设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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

迷鸟归林 2024-10-11 00:57:17

不确定什么会执行得更快,但是当涉及 .jpeg.html 等扩展时,这会更可靠

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

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

x.replace(/\.[^/.]+$/, "")
浪漫人生路 2024-10-11 00:57:17

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

const path = require('path');
const filename = 'hello.html';
    
path.parse(filename).name;     //=> "hello"
path.parse(filename).ext;      //=> ".html"
path.parse(filename).base; //=> "hello.html"

更多说明请参见 Node.js 文档 页面。

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

const path = require('path');
const filename = 'hello.html';
    
path.parse(filename).name;     //=> "hello"
path.parse(filename).ext;      //=> ".html"
path.parse(filename).base; //=> "hello.html"

Further explanation at Node.js documentation page.

草莓味的萝莉 2024-10-11 00:57:17

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

如果您不知道长度 @John Hartsock 正则表达式 将是正确的方法。

如果您不想使用正则表达式,可以尝试此操作(性能较低):

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

请注意,它对于没有扩展名的文件将失败。

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):

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

Note that it will fail on files without extension.

旧夏天 2024-10-11 00:57:17

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

编辑:

要回答......当然,如果您总是有 .jpg 的扩展名,x.length-4 就可以正常工作。

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

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

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

OR

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

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

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

OR (也可以只有一个点)

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

x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.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)

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

OR (also with only one dot)

parts = x.split(".");
x = parts[0];
遮了一弯 2024-10-11 00:57:17

我喜欢这一本,因为它是一本单行本,读起来并不太难:

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

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

filename.substring(0, filename.lastIndexOf('.')) || filename
去了角落 2024-10-11 00:57:17

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

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

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

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

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);
}
窝囊感情。 2024-10-11 00:57:17

在 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.

看透却不说透 2024-10-11 00:57:17

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

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.

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

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

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

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:

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

久光 2024-10-11 00:57:17

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

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"

也可以用作这样的单行:

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

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

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

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 + ""
}
断桥再见 2024-10-11 00:57:17

另一句:

x.split(".").slice(0, -1).join(".")

Another one-liner:

x.split(".").slice(0, -1).join(".")
月竹挽风 2024-10-11 00:57:17

如果您必须处理包含完整路径的变量(例如:thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg")并且您只想返回“ filename" 你可以使用:

theName = thePath.split("/").slice(-1).join().split(".").shift();

结果将是 theName == "filename";

要尝试将以下命令写入 chrome 调试器的控制台窗口:
window.location.pathname.split("/").slice(-1).join().split(".").shift()

如果您有仅处理文件名及其扩展名(例如:theNameWithExt = "filename.jpg"):

theName = theNameWithExt.split(".").shift();

结果将是theName == "filename",与多于;

注意:

  1. 第一个有点慢,因为执行更多
    运营;但在两种情况下都有效,换句话说它可以提取
    不带扩展名的文件名,来自包含路径或带有 ex 的文件名的给定字符串。而第二个仅当给定变量包含带有 ext 的文件名(如 filename.ext)时才有效,但速度要快一些。
  2. 这两种解决方案都适用于本地文件和服务器文件;

但我不能说与其他答案的性能比较,也不能说浏览器或操作系统兼容性。

工作片段 1:完整路径

var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
theName = thePath.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

工作片段 2:带扩展名的文件名

var theNameWithExt = "filename.jpg";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

工作片段 2:具有双扩展名的文件名

var theNameWithExt = "filename.tar.gz";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

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:

theName = thePath.split("/").slice(-1).join().split(".").shift();

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"):

theName = theNameWithExt.split(".").shift();

the result will be theName == "filename", the same as above;

Notes:

  1. The first one is a little bit slower cause performes more
    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.
  2. Both solutions work for both local and server files;

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

var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
theName = thePath.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

working snippet 2: the file name with extension

var theNameWithExt = "filename.jpg";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

working snippet 2: the file name with double extension

var theNameWithExt = "filename.tar.gz";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

故事还在继续 2024-10-11 00:57:17

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

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

这应该只截断最后一段。

Here's another regex-based solution:

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

This should only chop off the last segment.

风追烟花雨 2024-10-11 00:57:17

简单的一个:

var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;

Simple one:

var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
自此以后,行同陌路 2024-10-11 00:57:17

接受的答案仅删除最后一个扩展部分(.jpeg),这在大多数情况下可能是一个不错的选择。

我曾经不得不删除所有扩展名 (.tar.gz),并且文件名被限制为不包含点(因此 2015-01-01.backup.tar 不会是一个问题):

var name = "2015-01-01_backup.tar.gz";
name.replace(/(\.[^/.]+)+$/, "");

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 (so 2015-01-01.backup.tar would not be a problem):

var name = "2015-01-01_backup.tar.gz";
name.replace(/(\.[^/.]+)+$/, "");
帅哥哥的热头脑 2024-10-11 00:57:17
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
今天小雨转甜 2024-10-11 00:57:17
  • 如果您使用 Node.js,第一个评论中的答案就是一个简单的答案。
  • 我的任务是需要从 Node 服务器删除 Cloudinary 中的图像,并且只需要获取图像名称。
    例子:
const path = require("path")
const image=xyz.jpg;
const img= path.parse(image).name
console.log(img) // xyz
  • A straightforward answer, if you are using Node.js, is the one in the first comment.
  • My task was I need to delete an image in Cloudinary from the Node server and I just need to get the image name only.
    Example:
const path = require("path")
const image=xyz.jpg;
const img= path.parse(image).name
console.log(img) // xyz
梦行七里 2024-10-11 00:57:17

Node.js 从完整路径保留目录中删除扩展

https://stackoverflow.com/a/31615711/895245 例如,path/hello.html -> hello,但如果你想要path/hello.html -> path/hello,您也可以使用以下

#!/usr/bin/env node
const path = require('path');
const filename = 'path/hello.html';
const filename_parsed = path.parse(filename);
console.log(path.join(filename_parsed.dir, filename_parsed.name));

输出目录:

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 want path/hello.html -> path/hello, you can use this:

#!/usr/bin/env node
const path = require('path');
const filename = 'path/hello.html';
const filename_parsed = path.parse(filename);
console.log(path.join(filename_parsed.dir, filename_parsed.name));

outputs directory as well:

path/hello

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.

甚是思念 2024-10-11 00:57:17

虽然已经很晚了,但我将添加另一种方法来使用普通的旧 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('.')), '')

辞旧 2024-10-11 00:57:17

我们可能会遇到带有多个扩展名后缀的文件名或文件路径。请考虑以下事项来修剪它们。

text = "/dir/path/filename.tar.gz"    
output = text.replace(/(\.\w+)+$/,"")

输出结果:“/dir/path/filename”

它解决了文件扩展名问题,特别是当输入有多个扩展名时。

We might come across filename or file path with multiple extension suffix. Consider the following to trim them.

text = "/dir/path/filename.tar.gz"    
output = text.replace(/(\.\w+)+$/,"")

result of output: "/dir/path/filename"

It solves the file extension problem especially when the input has multiple extensions.

友谊不毕业 2024-10-11 00:57:17

这可能会有所帮助...

const splitNameAndExtension = (fileName) => {
  const dotIndex = fileName.lastIndexOf(".");

  if (dotIndex === -1) {
    return { name: fileName, extension: "" };
  }

  const name = fileName.substring(0, dotIndex);
  const extension = fileName.substring(dotIndex + 1);

  return { name, extension };
};

const result = splitNameAndExtension("File A (1).txt");
console.log("result: ", result) // { name: "File A (1)", extension: "txt" }

This might help...

const splitNameAndExtension = (fileName) => {
  const dotIndex = fileName.lastIndexOf(".");

  if (dotIndex === -1) {
    return { name: fileName, extension: "" };
  }

  const name = fileName.substring(0, dotIndex);
  const extension = fileName.substring(dotIndex + 1);

  return { name, extension };
};

const result = splitNameAndExtension("File A (1).txt");
console.log("result: ", result) // { name: "File A (1)", extension: "txt" }

旧伤慢歌 2024-10-11 00:57:17

这就是正则表达式派上用场的地方! Javascript 的 .replace() 方法将采用正则表达式,您可以利用它来完成您想要的操作:

// assuming var x = filename.jpg or some extension
x = x.replace(/(.*)\.[^.]+$/, "$1");

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:

// assuming var x = filename.jpg or some extension
x = x.replace(/(.*)\.[^.]+$/, "$1");
疯了 2024-10-11 00:57:17

您可以使用path来操纵。

var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
var MYEXT = '.js';
var fileName = path.basename(MYPATH, MYEXT);
var filePath = path.dirname(MYPATH) + '/' + fileName;

输出

> filePath
'/User/HELLO/WORLD/FILENAME'
> fileName
'FILENAME'
> MYPATH
'/User/HELLO/WORLD/FILENAME.js'

You can use path to maneuver.

var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
var MYEXT = '.js';
var fileName = path.basename(MYPATH, MYEXT);
var filePath = path.dirname(MYPATH) + '/' + fileName;

Output

> filePath
'/User/HELLO/WORLD/FILENAME'
> fileName
'FILENAME'
> MYPATH
'/User/HELLO/WORLD/FILENAME.js'
回忆躺在深渊里 2024-10-11 00:57:17

这是我用来从文件名中删除扩展名的代码,无需使用正则表达式或indexOf(IE8 不支持indexOf)。它假定扩展名是最后一个“.”之后的任何文本。特点。

它适用于:

  • 没有扩展名的文件:
  • 带有“.”的“myletter”文件名称中:“my.letter.txt”
  • 文件扩展名的长度未知:“my.letter.html”

以下是代码:

var filename = "my.letter.txt" // some filename

var substrings = filename.split('.'); // split the string at '.'
if (substrings.length == 1)
{
  return filename; // there was no file extension, file was something like 'myfile'
}
else
{
  var ext = substrings.pop(); // remove the last element
  var name = substrings.join(""); // rejoin the remaining elements without separator
  name = ([name, ext]).join("."); // readd the extension
  return name;
}

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:

  • files without an extension: "myletter"
  • files with '.' in the name: "my.letter.txt"
  • unknown length of file extension: "my.letter.html"

Here's the code:

var filename = "my.letter.txt" // some filename

var substrings = filename.split('.'); // split the string at '.'
if (substrings.length == 1)
{
  return filename; // there was no file extension, file was something like 'myfile'
}
else
{
  var ext = substrings.pop(); // remove the last element
  var name = substrings.join(""); // rejoin the remaining elements without separator
  name = ([name, ext]).join("."); // readd the extension
  return name;
}
天涯离梦残月幽梦 2024-10-11 00:57:17

我喜欢使用正则表达式来做到这一点。它简短且易于理解。

for (const regexPattern of [
  /\..+$/,  // Find the first dot and all the content after it.
  /\.[^/.]+$/ // Get the last dot and all the content after it.
  ]) {
  console.log("myFont.ttf".replace(regexPattern, ""))
  console.log("myFont.ttf.log".replace(regexPattern, ""))
}

/* output
myFont
myFont
myFont
myFont.ttf
*/

上面的解释可能不是很严谨。如果想得到更准确的解释可以去regex101查看

I like to use the regex to do that. It's short and easy to understand.

for (const regexPattern of [
  /\..+$/,  // Find the first dot and all the content after it.
  /\.[^/.]+$/ // Get the last dot and all the content after it.
  ]) {
  console.log("myFont.ttf".replace(regexPattern, ""))
  console.log("myFont.ttf.log".replace(regexPattern, ""))
}

/* output
myFont
myFont
myFont
myFont.ttf
*/

The above explanation may not be very rigorous. If you want to get a more accurate explanation can go to regex101 to check

友谊不毕业 2024-10-11 00:57:17

在节点中:

const path = require('path');
path.join(path.dirname(filename), path.parse(filename).name)

或者如果您想确保删除特定扩展名(但仅当存在时)

const path = require('path');
path.join(path.dirname(filename), path.basename(filename, '.ext'))

为什么上述:

  • 保留完整文件路径,
  • 它与操作系统无关(您不需要显式提供分隔符)
  • 当目录有点但文件名没有时,两种形式都是安全的,
  • 对于文件名可能有点但实际扩展名由于某种原因丢失的情况,第二种形式也是安全的,

例如

let filename='path/to/my.file'

path.join(path.dirname(filename), path.basename(filename, '.doc'))
//Result:   path/to/my.file  (and not path/to/my)

In node:

const path = require('path');
path.join(path.dirname(filename), path.parse(filename).name)

or if you want to make sure that you remove a specific extension (but only if present)

const path = require('path');
path.join(path.dirname(filename), path.basename(filename, '.ext'))

why the above:

  • The full file path is kept
  • it is os-independent (you don't need to explicitly provide the separator)
  • both forms are safe when directories have dots but filename does not
  • the second form is also safe for cases where filename may have dots but the actual extension is for some reason missing

e.g.

let filename='path/to/my.file'

path.join(path.dirname(filename), path.basename(filename, '.doc'))
//Result:   path/to/my.file  (and not path/to/my)

洋洋洒洒 2024-10-11 00:57:17

另一张衬垫 - 我们假设我们的文件是一张 jpg 图片>>>例如:var yourStr = 'test.jpg';

    yourStr = yourStr.slice(0, -4); // 'test'

Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';

    yourStr = yourStr.slice(0, -4); // 'test'
待天淡蓝洁白时 2024-10-11 00:57:17
x.slice(0, -(x.split('.').pop().length + 1));
x.slice(0, -(x.split('.').pop().length + 1));
违心° 2024-10-11 00:57:17

试试这个
.split('.')[0]

它对我有用

Try this one
.split('.')[0]

it worked for me

GRAY°灰色天空 2024-10-11 00:57:17
name.split('.').slice(0, -1).join('.')

这就是全部享受你的编码......

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

that's all enjoy your coding...

下壹個目標 2024-10-11 00:57:17

我会使用类似 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文