如何从 Javascript 中的任意字符串生成有效的文件名?

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

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

结果应尽可能接近原始字符串,以便于人类阅读(因此 slugify is not an option). This means it needs only to replace characters which are not supported by an OS

例如:

'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