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

javascript-从字符串中消除超出范围的ASCII字符

(javascript - Eliminating out-of-range ASCII characters from string)

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

使用JavaScript,我想减少一个字符串,使其仅包含ASCII 65-90(AZ中的大写字母)内的字符。

我的功能从将字符串变成大写开始。接下来消除空格,最后将字母转换为ASCII小数。

我只想要字母AZ(ASCII 65-90),别无其他。但是,如果字符串包含一个或多个不想要的字符怎么办?有没有办法从字符串中消除字符<ASCII 65和>ASCII 90的所有实例

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

你可以使用一个简单的reduce调用:

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

console.log({ input, output })