st_phan
st_phan

Reputation: 904

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

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!

Upvotes: 6

Views: 7704

Answers (3)

Hien Nguyen
Hien Nguyen

Reputation: 589

Use string replace function

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, ""));

Or expect number and letter

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

Upvotes: 4

st_phan
st_phan

Reputation: 904

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

Upvotes: 1

Kelvin A.
Kelvin A.

Reputation: 16

When you assign a value to the variable, you use a single quote ', in which the string will break if you have another ' in your string. You need to add a backslash \ before the single quote inside when you declare the string.

However, if the string you are using is got from somewhere, then you don't need to add a backslash because it's probably handled well in another place.

Note that / \ : * ? " < > | are not allowed for filename.

So if the value is set in a variable already, you need to remove all these characters. Do this

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

Upvotes: 0

Related Questions