I have the following regex
/(\.|\/)(gif|jpe?g|png)$/i
Which works for fileNames
in ensuring on gif
, jpeg
and png
's are accepted. However, I want to extend this code to also check fileNames
and开发者_如何学运维 ensure they don't contain dangerous
characters like
!@#$%^&*()
- How can I do this ?
- How can I "replace" these with "" ?
It's better to only allow a specific set of characters instead of denying every possible dangerous character, as you possibly don't know all possible dangerous characters. You know, however, all the characters you want to allow.
Use this:
/^\w+(\.|\/)(gif|jpe?g|png)$/i
This ensures that the filename contains only non-dangerous characters (letter, numbers and _).
You could also remove not allowed characters:
name = name.replace(/[^\w.]+/g, '')
This regex will only match if none of the undesired characters are present
/^[^!@#\$%\^&\*\(\)]*$/
I would actually do this separately; first use the regex to ensure the proper extension, and then plain old indexOf
on each character to test for it in the string. However, you can also use a lookahead, which JavaScript supports:
/^(?!.*[!@#$%^&*()]).*(\.|\/)(gif|jpe?g|png)$/i
精彩评论