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 badges2 Answers
Reset to default 9This 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.
本文标签:
版权声明:本文标题:regex - Allow only alphanumeric, dash, underscore, and period in string (Javascript) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741612043a2388316.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论