In this article, we are given a string containing some Non-ASCII characters and the task is to remove all Non-ASCII characters from the given string. There are two methods to solve this problem which are discussed below:
Approaches to remove all Nom-ASCII Characters from String:
Approach 1: Using ASCII values in JavaScript regEx
- This approach uses a Regular Expression to remove the Non-ASCII characters from the string.
- Only characters that have values from zero to 127 are valid. (0x7F is 127 in hex).
- Use the .replace() method to replace the Non-ASCII characters with the empty string.
Example: This example implements the above approach.
Javascript
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter" ;
console.log(str);
function gfg_Run() {
str = str.replace(/[^\x00-\x7F]/g, "" );
console.log(str);
}
gfg_Run();
|
Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character
- This approach uses a Regular Expression to remove the Non-ASCII characters from the string like in the previous example.
- It specifies the Unicode for the characters to remove. The range of characters between (0080 – FFFF) is removed.
- Use .replace() method to replace the Non-ASCII characters with the empty string.
Example: This example implements the above approach.
Javascript
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter" ;
console.log(str);
function gfg_Run() {
str = str.replace(/[\u{0080}-\u{FFFF}]/gu, "" );
console.log(str);
}
gfg_Run();
|
Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character
Approach 3: Using ASCII values with the Array filter method
This approach uses the Array filter along with the JavaScript split method to filter out the ASCII-valid characters from the input string.
Example: This example demonstrates the above approach.
Javascript
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter" ;
console.log(str);
function gfg_Run() {
str = str
.split( "" )
.filter( function (char) {
return char.charCodeAt(0) <= 127;
})
.join( "" );
console.log(str);
}
gfg_Run();
|
Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Jul, 2023
Like Article
Save Article