Match non printable/non ascii characters and remove from text

后端 未结 4 2094
别跟我提以往
别跟我提以往 2020-12-04 22:30

My JavaScript is quite rusty so any help with this would be great. I have a requirement to detect non printable characters (control characters like SOH, BS etc) as well exte

4条回答
  •  执笔经年
    2020-12-04 22:41

    To target characters that are not part of the printable basic ASCII range, you can use this simple regex:

    [^ -~]+
    

    Explanation: in the first 128 characters of the ASCII table, the printable range starts with the space character and ends with a tilde. These are the characters you want to keep. That range is expressed with [ -~], and the characters not in that range are expressed with [^ -~]. These are the ones we want to replace. Therefore:

    result = string.replace(/[^ -~]+/g, "");
    

提交回复
热议问题