I'm using JavaScript RegEx to filter input (white list only acceptable chars). As .match() returns an array, the best way I found to 'glue' back together the string is as follows, which seems ugly, as then I have to remove the ma.
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 the array (e.g. like .join in Ruby)?
Thanks Brian
I'm using JavaScript RegEx to filter input (white list only acceptable chars). As .match() returns an array, the best way I found to 'glue' back together the string is as follows, which seems ugly, as then I have to remove the ma.
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 the array (e.g. like .join in Ruby)?
Thanks Brian
Share Improve this question edited Mar 5, 2011 at 17:41 NullUserException 85.5k31 gold badges211 silver badges237 bronze badges asked Mar 5, 2011 at 17:39 Brian LedsworthBrian Ledsworth 312 bronze badges1 Answer
Reset to default 10There is a join
in JavaScript as well. For instance:
myString.match(/[A-Za-z-_0-9]/g).join("")
The ""
is the separator between each element of the array, so [1, 2, 3].join("")
gives "123"
. However, you could also simply replace all characters not in your whitelist:
myString.replace(/[^A-Za-z-_0-9]/g, "")
Which will simply remove any character that isn't alphanumeric, a dash, or an underscore.