Removing invalid characters in JavaScript

后端 未结 3 825
一个人的身影
一个人的身影 2020-12-29 05:30

Can someone provide a regular expression to search and replace illegal characters found

Example, removing �

I am not sure how many types of \'illegal\' char

相关标签:
3条回答
  • 2020-12-29 05:57

    Instead of having a blacklist, you could use a whitelist. e.g. If you want to only accept letters, numbers, space, and a few punctuation characters, you could do

    myString.replace(/[^a-z0-9 ,.?!]/ig, '')
    
    0 讨论(0)
  • 2020-12-29 06:02

    Invalid characters get converted to 0xFFFD on parsing, so any invalid character codes would get replaced with:

    myString = myString.replace(/\uFFFD/g, '')
    

    You can get all types of invalid sorts of chars here

    0 讨论(0)
  • 2020-12-29 06:13

    Try this, it will work for all unexpected character like ♫ ◘ etc...

    dataStr.replace(/[\u{0080}-\u{FFFF}]/gu,"");
    
    0 讨论(0)
提交回复
热议问题