Warm tip: This article is reproduced from serverfault.com, please click

Eliminating out-of-range ASCII characters from string

发布于 2020-12-08 10:44:07

Using JavaScript, I want to reduce a string to include characters within ASCII 65-90 only (uppercase letters from A-Z).

My function starts with turning the string into full uppercase. Spaces are eliminated next and finally, letters are converted to ASCII decimals.

I want letters A-Z only (ASCII 65-90), nothing else. What if the string, however, does contain one or more non-desired characters? Is there a way to eliminate all instances of characters < ASCII 65 and > ASCII 90 from a string?

Questioner
kityatyi
Viewed
0
Terry Lennox 2020-12-08 19:46:12

You could use a simple reduce call:

const input = "asddgAeBcc6$$Cz>>,,";
const output = Array.prototype.reduce.call(input, (res, c) => res + ((c >= 'A' && c <= 'Z') ? c: ""), "");

console.log({ input, output })