views:

38

answers:

3

Need a function to strip off a set of illegal character in javascript: |&;$%@"<>()+,

This is a classic problem to be solved with regexes, which means now I have 2 problems.

This is what I've got so far:

var cleanString = dirtyString.replace(/\|&;\$%@"<>\(\)\+,/g, "");

I am escaping the regex special chars with a backslash but I am having a hard time trying to understand what's going on.

If I try with single literals in isolation most of them seem to work, but once I put them together in the same regex depending on the order the replace is broken.

i.e. this won't work --> dirtyString.replace(/\|<>/g, ""):

Help appreciated!

+2  A: 

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
ChaosPandion
+1  A: 

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
Darin Dimitrov
+4  A: 

What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).

Syntax: [characters] where characters is a list with characters.

Example:

var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
Lekensteyn
are escape chars not needed within the character class?
JohnIdol
No, only for `]` and `\` (and `^` unless you put it anywhere other than in the first position, and `-` unless you put it first or last).
Tim Pietzcker