如何从 JavaScript 中的任意字符串创建有效的文件名?

st_*_*han 6 javascript compatibility parsing

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

\n\n

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

\n\n

例如:

\n\n
\'Article: "Un \xc3\xa9l\xc3\xa9phant \xc3\xa0 l\\\'or\xc3\xa9e du bois/An elephant at the edge of the woods".txt\'\n\xe2\x86\x92 \'Article   Un \xc3\xa9l\xc3\xa9phant \xc3\xa0 l\\\'or\xc3\xa9e du bois An elephant at the edge of the woods .txt\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

st_*_*han 0

非常感谢凯尔文的回答!

\n\n

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

\n\n
function convertToValidFilename(string) {\n    return (string.replace(/[\\/|\\\\:*?"<>]/g, " "));\n}\n\nvar string = \'Un \xc3\xa9l\xc3\xa9phant \xc3\xa0 l\\\'or\xc3\xa9e du bois/An elephant at the edge of the woods".txt\';\n\nconsole.log("Before = ", string);\nconsole.log("After  = ", convertToValidFilename(string));\n
Run Code Online (Sandbox Code Playgroud)\n\n

这导致输出:

\n\n
Before =  Un \xc3\xa9l\xc3\xa9phant \xc3\xa0 l\'or\xc3\xa9e du bois/An elephant at the edge of the woods".txt\nAfter  =  Un \xc3\xa9l\xc3\xa9phant \xc3\xa0 l or\xc3\xa9e du bois An elephant at the edge of the woods .txt\n
Run Code Online (Sandbox Code Playgroud)\n