最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript RegEx to white list chars, how bad is my approach? - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论