Bill Dailey
Bill Dailey

Reputation: 43

Allow only alphanumeric, dash, underscore, and period in string (Javascript)

I'm writing a file upload page script (Javascript). The user selects a file from their machine.

I need to strip out anything from the string containing the file name that is not:

I have been trying to use the Javascript replace function to remove the unnecessary characters. I am able to remove all the non-alphanumeric parts using:

rawFilename = data.files[0].name;  
safeFilename = rawFilename.replace(/\W/g, '');

That leaves in the letter, numbers, and underscore, but I need to also allow dash and periods. I'm not sure what the correct regex to select the dash and periods as well would be.

Upvotes: 0

Views: 6209

Answers (2)

1.21 gigawatts
1.21 gigawatts

Reputation: 17770

Adding to the previous answer by Lucas

str = str.replace(/[^\w\.\-]/g, "");

Dashes and periods can be any location.

Upvotes: 2

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

This is pretty simple using a negative character class:

str = str.replace(/[^\w.-]+/g, "");

The only gotcha is that the - needs to be either first or last in the list, because it can be interpreted as the range operator.

Upvotes: 9

Related Questions