Javascript string replace with regex to strip off illegal characters

JavascriptRegexString

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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, "");

Solution 2 - Javascript

I tend to look at it from the inverse perspective which may be what you intended:

What characters do I want to allow?

This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.

For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:

"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"

Solution 3 - Javascript

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, "");

Solution 4 - Javascript

Put them in brackets []:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnIdolView Question on Stackoverflow
Solution 1 - JavascriptLekensteynView Answer on Stackoverflow
Solution 2 - JavascriptJohn CulvinerView Answer on Stackoverflow
Solution 3 - JavascriptChaosPandionView Answer on Stackoverflow
Solution 4 - JavascriptDarin DimitrovView Answer on Stackoverflow