Home > Software design >  js: using replace method to strip string of all non-alpha numeric with exceptions?
js: using replace method to strip string of all non-alpha numeric with exceptions?

Time:11-15

I am creating a storage path and using replace(/[^a-z0-9]/gi, '') to remove all non-alpha numeric characters from a string but now I want to allow - and _ , since those are valid in paths. How can I modify my replace method to have it remove all non-alpha numeric characters with the exception of - and _ ?

CodePudding user response:

Since your regex says to "replace every char EXCEPT these ones", add them to your regex, as so:

replace(/[^a-z0-9-_]/gi, '')
//               ^

Both hyphen and underscore characters don't need any escape sequences. However, in order to stop the regex from ever confusing the hyphen for a range of characters, you can also add a \ to escape the hyphen:

replace(/[^a-z0-9\-_]/gi, '')
//               ^ extra backslash
  • Related