admin管理员组

文章数量:1296914

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:

  • A letter
  • A number
  • a dash
  • an underscore
  • A period

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.

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:

  • A letter
  • A number
  • a dash
  • an underscore
  • A period

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.

Share Improve this question asked Nov 25, 2014 at 0:40 Bill DaileyBill Dailey 431 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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.

Adding to the previous answer by Lucas

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

Dashes and periods can be any location.

本文标签: