views:

68

answers:

4

I would like some help creating a regular expression for parsing a string on a textbox. I currently have these two javascript methods:

function removeIllegalCharacters(word) {
    return word.replace(/[^a-zA-Z 0-9,.]/g, '');
}

$("#comment").keyup(function() {
 this.value = removeIllegalCharacters(this.value);
}); 

I would like to replace my /[^a-zA-Z 0-9,.]/g regex for one that would accept only the following set of characters:

  • a-z
  • A-Z
  • 0-9
  • áéíóúü
  • ÁÉÍÓÚÜ
  • ñÑ
  • ;,.
  • ()
  • - +

It's probably pretty simple, but I have close to none regex skills. Thanks in advance.

A: 
return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');

You may have to use the hex escape sequence (\x##) or unicode escape sequence (\u####) for some of the non standard letters, but that will give you a good start. Or, slightly simplified:

return word.replace(/[^\w\dáéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');
Sparafusile
I think you want `^` inside the character class. Also, `\w` will match an underscore character which wasn't specified in the list.
Andy E
`\w` contains `\d`. Also, you forgot `+` and `-`. Plus, no need to escape `().`.
Tim Pietzcker
A: 

If I've understood your requirements correctly, you want to allow only the listed char and you want to delete rest all char. If that is the case you can simply extend your char class as:

function removeIllegalCharacters(word) {
    return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ;,.()]/g, '');
}
codaddict
+2  A: 

Just add those characters in.

function removeIllegalCharacters(word) {
    return word.replace(/[^a-zA-Z 0-9,.áéíóúüÁÉÍÓÚÜñÑ();+-]/g, '');
}
patrick dw
A: 

Did you try with: [^a-zA-Z 0-9;,.áéíóúüÁÉÍÓÚÜñÑ()]

watbywbarif