简体   繁体   中英

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:

  • 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM