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 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 the array (e.g. like .join in Ruby)?
Thanks Brian
There 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.
精彩评论