0

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;
});
1
  • Not sure your first part is done right. Try with "a ,b, c,d , e,f " as input, the result will be "a,b, c,d , e,f". Commented Nov 6, 2014 at 13:28

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up doing this, thank you! var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1,$2').replace(/[^\w,]/g, '');
0

Try this:

var str = this.value.replace(/\s/g, ',').replace(/[^\w,]/g, '');

2 Comments

a , b would become a,,,b. I don't think this is what the OP wanted.
Well, I think it's exactly what OP asked - "the first is remove any spaces and replace it with a comma separator"... whether an empty string is also a word was not defined in the question, as well as what to do with spaces surrounding commas. But yeah, probably he wanted only one comma between real words.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.