crunch crunch -4 years ago 181
Javascript Question

JavaScript regex to remove special characters and remove extra spaces while leaving commas

I'm trying to do two things to clean the string, the first is to remove any space and replace it with a comma separator, the second is to remove any non-alphanumeric characters (other than the comma); I have the first part functional, but now I can't figure out how to remove the special characters as well:

$("#fancydiv").keyup(function(e) {
var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1,$2');
if (str!=this.value) this.value = str;

Answer Source
'?no, special-characters!'.replace(/[^\w,]/g, '')
// => "no,specialcharacters"

[^\w,] will match match non-alphabet, non-digit, non-underscore character excluding a comma.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download