Is there a way to convert an arbitrary string to a valid filename in Javascript?
The result should stick as close to the original string as possible, to be easy for humans to read (therefore slugify is not an option). This means it needs only to replace characters which are not supported by an OS.
For example:
'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'
I thought that this would be a common problem, but I haven't found any solutions to it. I hope you can help me!
Huge thanks to Kelvin's answer!
I quickly compiled it into a function. The final code I used is:
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));
This results in the output:
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