Javascript string replace with regex to strip off illegal characters

前端 未结 4 1257
挽巷
挽巷 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 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"
    

提交回复
热议问题