RegEx JavaScript for whitelisting, how bad is my approach?

I use JavaScript RegEx to filter input (whitelist - only acceptable characters). Since .match () returns an array, the best way I found to “glue” back is the next line, which seems ugly, since then I need to remove the comma.

myString.match(/[A-Za-z-_0-9]/g).toString().replace(/,/g,'')

Is there a better RegEx approach in JS, or a better way to handle an array (e.g. like .join in Ruby)?

Thanks Brian

+3
source share
1 answer

In JavaScript there is join. For instance:

myString.match(/[A-Za-z-_0-9]/g).join("")

""is a separator between each element of the array, therefore [1, 2, 3].join("")gives "123". However, you can also simply replace all characters not in your whitelist:

myString.replace(/[^A-Za-z-_0-9]/g, "")

, -, .

+10

Source: https://habr.com/ru/post/1796525/


All Articles