Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 _ ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading