如何在 Javascript 中从任意字符串制作有效的文件名

How to make a valid filename from an arbitrary string in Javascript?

本文关键字:有效 文件名 字符串 任意 Javascript      更新时间:2023-09-26

有没有办法在Javascript中将任意字符串转换为有效的文件名?

结果应尽可能接近原始字符串,以便于人类阅读(因此 slugify 不是一种选择)。这意味着它只需要替换操作系统不支持的字符。

例如:

'Article: "Un éléphant à l''orée du bois/An elephant at the edge of the woods".txt'
→ 'Article   Un éléphant à l''orée du bois An elephant at the edge of the woods .txt'

我以为这将是一个常见问题,但我还没有找到任何解决方案。希望你能帮到我!

使用字符串替换函数

var str = 'Article: "Un éléphant à l'orée du bois/An elephant at the edge of the woods".txt';
var out = (str.replace(/[ &'/''#,+()$~%.'":*?<>{}]/g, ""));

或者期待数字和字母

var out=(str.replace(/[^a-zA-Z0-9]/g, ''));

当您为变量赋值时,请使用单引号 ',如果字符串中有另一个 ',则字符串将中断。声明字符串时,需要在单引号之前添加反斜杠 ''。

但是,如果您使用的字符串是从某个地方获取的,则无需添加反斜杠,因为它可能在另一个地方处理得很好。

请注意/'' : * ?'" <> |不允许用于文件名。

因此,如果已经在变量中设置了该值,则需要删除所有这些字符。这样做

    var str = 'Article: "Un éléphant à l''orée du bois/An elephant at the edge of the woods".txt';
    str = str.replace(/['/'':*?"<>]/g, ""));

非常感谢开尔文的回答!

我很快将其编译成一个函数。我使用的最终代码是:

function convertToValidFilename(string) {
    return (string.replace(/['/|'':*?"<>]/g, " "));
}
var string = 'Un éléphant à l''orée du bois/An elephant at the edge of the woods".txt';
console.log("Before = ", string);
console.log("After  = ", convertToValidFilename(string));

这将产生输出:

Before =  Un éléphant à l'orée du bois/An elephant at the edge of the woods".txt
After  =  Un éléphant à l orée du bois An elephant at the edge of the woods .txt