How to remove all Non-ASCII characters from the string using JavaScript ?
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:
Approach 1:
- 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.
html
< body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run()" > Click Here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str="Hidd©©©en??Ascii ©©®®®Charac££ter"; el_up.innerHTML = "Click on the button to remove" + " the all Non-ASCII characters from the" + " given string.< br >Str = '" + str + "'"; function gfg_Run() { str = str.replace(/[^\x00-\x7F]/g, ""); el_down.innerHTML = str; } </ script > </ body > |
Output:

Remove all Non-ASCII characters from the string
Approach 2:
- 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.
html
< body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run()" > Click Here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str="Hidd©©©en??Ascii ©©®®®Charac££ter"; el_up.innerHTML = "Click on the button to remove" + " the all Non-ASCII characters from the" + " given string.< br >Str = '" + str + "'"; function gfg_Run() { str = str.replace(/[\u{0080}-\u{FFFF}]/gu, ""); el_down.innerHTML = str; } </ script > </ body > |
Output:

Remove all Non-ASCII characters from the string
Please Login to comment...