Javascript string replace with regex to strip off illegal characters

前端 未结 4 1254
挽巷
挽巷 2020-12-14 05:11

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

This is a classic problem to be solved with regexes, whi

相关标签:
4条回答
  • 2020-12-14 05:57

    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, "");
    
    0 讨论(0)
  • 2020-12-14 05:59

    Put them in brackets []:

    var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
    
    0 讨论(0)
  • 2020-12-14 06:11

    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, "");
    
    0 讨论(0)
  • 2020-12-14 06:16

    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"
    
    0 讨论(0)
提交回复
热议问题