简体   繁体   中英

Regex to match specific non-printable characters on the ASCII table

I am writing a function that checks if the decimal value of a character is printable, and returns a symbol if it is not printable. On the ASCII table, decimal values 0 to 31 and 127 are non-printable, but I want the symbol returned for these specific decimal values only (0-8, 11, 12, 16-19,21-31, 127). How can I better my code using regex? I am also willing to learn any optimization you can suggest.

function replaceNonPrintableWithSymbol(character) {
  let noEntrySymbol = "\u26D4";
  let characterDecimalValue = character.charCodeAt();
  let specificNonPrintableValues = [0,1,2,3,4,5,6,7,8,11,12,16,17,18,19,21,22,23,24,25,26,27,28,29,30,31,127];
  let isWithinRange = specificNonPrintableValues.includes(characterDecimalValue);

  return isWithinRange? noEntrySymbol : character;
}

You need to create a character class containing all the characters you want to replace [ - , , , - , - , ] should do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM