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 :
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