JavaScript 如何删除字符串中的所有非ASCII字符
在本文中,我们给定了一个包含一些非ASCII字符的字符串,并且任务是从给定的字符串中删除所有非ASCII字符。解决这个问题有两种方法,下面将进行讨论:
删除字符串中所有非ASCII字符的方法:
- 使用JavaScript正则表达式中的ASCII值
- 使用JavaScript正则表达式中的Unicode
- 使用数组过滤器中的ASCII值
方法1:使用JavaScript正则表达式中的ASCII值
- 这种方法使用一个 正则表达式 来从字符串中删除非ASCII字符。
- 只有值从零到127的字符是有效的。(0x7F在十六进制中代表127)。
- 使用 .replace()方法 将非ASCII字符替换为空字符串。
示例: 这个示例实现了上述方法。
// Input String
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter";
// Display input string
console.log(str);
// Function to remove ASCII characters
// and display the output
function gfg_Run() {
// Using RegEx and replace method
// with Ascii values
str = str.replace(/[^\x00-\x7F]/g, "");
// Display output
console.log(str);
}
// Funcion call
gfg_Run();
输出
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character
方法2:在JavaScript正则表达式中使用Unicode
- 此方法使用一个 正则表达式 从字符串中移除非ASCII字符,和之前的示例类似。
- 它指定了需要移除的字符的Unicode。字符范围在(0080 – FFFF)之间。
- 使用 .replace()方法 将非ASCII字符替换为空字符串。
示例: 这个示例实现了上面的方法。
// Input String
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter";
// Display input string
console.log(str);
// Function to remove ASCII characters
// and display the output
function gfg_Run() {
// Using RegEx and replace method with Unicodes
str = str.replace(/[\u{0080}-\u{FFFF}]/gu, "");
// Display output
console.log(str);
}
// Funcion call
gfg_Run();
输出
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character
方法3:使用带有数组过滤器的ASCII值
这种方法使用 数组过滤器 以及 JavaScript split 方法来过滤输入字符串中的ASCII有效字符。
示例: 此示例演示了上述方法。
// Input String
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter";
// Display input string
console.log(str);
// Funciot to remove ASCII characters
// and display the output
function gfg_Run() {
// Using array.filter with ASCII values
str = str
.split("")
.filter(function (char) {
return char.charCodeAt(0) <= 127;
})
.join("");
// Display output
console.log(str);
}
// Funcion call
gfg_Run();
输出
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character