The Wayback Machine - https://web.archive.org/web/20241003184402/https://www.geeksforgeeks.org/how-to-remove-all-non-ascii-characters-from-the-string-using-javascript/
Open In App

How to remove all Non-ASCII characters from the string using JavaScript ?

Last Updated : 16 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Approaches to remove all Non-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
// 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();

Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character

Approach 2: Using Unicode in JavaScript regEx

  • 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
// 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();

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
// 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();

Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character

Approach 4: Using ES6 methods with a custom function

This approach utilizes the String.prototype.replace() method with a custom function that removes non-ASCII characters from the string.

JavaScript
// Input String
let str = "Hidd©©©en??Ascii ©©®®®Charac££ter";
// Display input string
console.log(str);

// Function to remove non-ASCII characters
function removeNonASCII(input) {
    return input.replace(/[^\x00-\x7F]/g, "");
}

// Function to remove non-ASCII characters
// and display the output
function gfg_Run() {
    // Using custom function with replace method
    str = removeNonASCII(str);
    
    // Display output
    console.log(str);
}

// Function call
gfg_Run();

Output
Hidd©©©en??Ascii ©©®®®Charac££ter
Hidden??Ascii Character




Similar Reads

Check if a string contains a non-ASCII value in Julia - ascii() Method
The ascii() is an inbuilt function in Julia which is used to convert a specified string to a String type and also check the presence of ASCII data. If the non-ASCII byte is present, throw an ArgumentError indicating the position of the first non-ASCII byte. Syntax: ascii(s::AbstractString) Parameters:s::AbstractString: Specified stringReturns: It r
1 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read
Remove k characters in a String such that ASCII sum is minimum
Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2 characters from the string "ABbc" to minimize the
7 min read
Python Encode Unicode and non-ASCII characters into JSON
This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understanding of how to work with Unicode and non-ASCII charac
5 min read
Transliterating non-ASCII characters with Python
Transliteration is a process of writing the word of one language using similarly pronounced alphabets in other languages. It deals with the pronunciation of words in other languages. Similarly, in computer language, the computer can handle ASCII characters but has problems with non-ASCII characters. There are some times when we are unable to skip n
3 min read
What is ASCII - A Complete Guide to Generating ASCII Code
The American Standard Code for Information Interchange, or ASCII, is a character encoding standard that has been a foundational element in computing for decades. It plays a crucial role in representing text and control characters in digital form. Historical BackgroundASCII has a rich history, dating back to its development in the early 1960s. Origi
13 min read
Substring with maximum ASCII sum when some ASCII values are redefined
Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters. Note: Uppercase & lowercase both will be present in the string W. Input: W = "abcde", N = 1,
9 min read
ASCII NULL, ASCII 0 ('0') and Numeric literal 0
The ASCII (American Standard Code for Information Interchange) NULL and zero are represented as 0x00 and 0x30 respectively. An ASCII NULL character serves as a sentinel character of strings in C/C++. When the programmer uses '0' in his code, it will be represented as 0x30 in hex form. What will be filled in the binary integer representation in the
3 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
JavaScript Program to Remove Non-Alphanumeric Characters from a String
We will see how to remove non-alphanumeric characters from a string in JavaScript. Non-alphanumeric characters are symbols, punctuation, and whitespace. Removing them from a string This task can be useful when you want to clean up user inputs, sanitize strings, or perform various text processing operations. There are multiple approaches to removing
4 min read
Longest string in non-decreasing order of ASCII code and in arithmetic progression
Given a non-empty string S of uppercase alphabets of length L the task is to find the longest string from the given string with characters arranged in descending order of their ASCII code and in arithmetic progression such that the common difference should be as low as possible and the characters of the string to be of higher ASCII value. Note: The
10 min read
Convert all lowercase characters to uppercase whose ASCII value is co-prime with k
Given an integer 'k' and a string 'str' consisting of characters from English alphabets. The task is to convert all lower case character to uppercase whose ASCII value is co-prime with k. Examples: Input: str = "geeksforgeeks", k = 4 Output: GEEKSfOrGEEKS 'f' and 'r' are the only characters whose ASCII values aren't co-prime with 4. Input: str = "A
6 min read
Increase the ASCII value of characters of the string by the given values
Content Removed
1 min read
Maximize ascii sum removing K characters in String
Given a string s and an integer K, the task is to remove K characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is maximized. Examples: Input: s = "word", K = 2Output: 233Explanation: We need to remove exactly 2 characters from the string "word" to maximize the
9 min read
Sort the string as per ASCII values of the characters
Given a string S of size N, the task is to sort the string based on its ASCII values. Examples: Input: S = "Geeks7"Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets. Input: S = "GeeksForGeeks"Output: FGGeeeekkorss Approach: The idea to solve this problem is to maintain an
6 min read
Count pairs of characters in a string whose ASCII value difference is K
Given string str of lower case alphabets and a non-negative integer K. The task is to find the number of pairs of characters in the given string whose ASCII value difference is exactly K. Examples: Input: str = "abcdab", K = 0 Output: 2 (a, a) and (b, b) are the only valid pairs.Input: str = "geeksforgeeks", K = 1 Output: 8 (e, f), (e, f), (f, e),
7 min read
Count characters in a string whose ASCII values are prime
Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime. Examples: Input: S = "geeksforgeeks" Output : 3 'g', 'e' and 'k' are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively. Input: S = "abcdefghijklmnopqrstuvwxyz" Output: 6 Approach: The idea is to gen
6 min read
Average of ASCII values of characters of a given string
Given a string, the task is to find the average of ASCII values of characters in the string. Examples: Input: str = "for"Output: 109'f'= 102, 'o' = 111, 'r' = 114(102 + 111 + 114)/3 = 109 Input: str = "geeks" Output: 105 Source: Microsoft Internship Experience Approach: Start iterating through characters of the string and add their ASCII value to a
5 min read
Program to find the largest and smallest ASCII valued characters in a string
Given a string of lowercase and uppercase characters, your task is to find the largest and smallest alphabet (according to ASCII values) in the string. Note that in ASCII, all capital letters come before all small letters. Examples : Input : sample stringOutput : Largest = t, Smallest = aInput : GeeksOutput : Largest = s, Smallest = GExplanation: A
6 min read
JavaScript Strip all non-numeric characters from string
In this article, we will strip all non-numeric characters from a string. In order to remove all non-numeric characters from a string, replace() function is used. Methods to Strip all Non-Numeric Characters from String:Table of Content Methods to Strip all Non-Numeric Characters from String:Method 1: Using JavaScript replace() FunctionMethod 3: Usin
3 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensuring all characters are the same. Given a string c
3 min read
How to validate if input in input field has ASCII characters using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can als
4 min read
Smallest Window in a String Containing all the Characters of Another String using JavaScript
Given two strings, "str" (the larger string) and "pattern" (the smaller string), the task is to find the smallest window in "str" that contains all the characters of "pattern" in any order using JavaScript. Examples: Input: str = "ADOBECODEBANC"pattern = "ABC"Output: BANCInput: str = "this is a test string"pattern = "tist";Output: t striTable of Co
3 min read
How to remove non-alphanumeric characters in PHP?
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found. Examples: Input : !@GeeksforGeeks2018? Output : GeeksforGeeks2018 Input : Geeks For Geeks Output
2 min read
Queries to calculate sum of squares of ASCII values of characters of a substring with updates
Given a string S of length N and a 2D array of strings Q[][] consisting of M queries of the following type: Query("U", "I", "X"): Update the character at index I with the character X.Query("S", "L", "R"): Print the sum of the squares of the position of the characters in the substring {S[L], ...., S[R]} according to the English alphabets. Examples:
15+ min read
Converting an Integer to Ascii Characters in Python
In Python, working with integers and characters is a common task, and there are various methods to convert an integer to ASCII characters. ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents text in computers. In this article, we will explore some simple and commonly used methods for convertin
3 min read
Sort an array of strings in increasing order of sum of ASCII values of characters
Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of the ASCII (American Standard Code for Information Interchange) value of their characters. Examples: Input: arr[] = {"for", "geeks", "app", "best"}Output: app for best geeksExplanation:Sum of ASCII values of characters of each string is: {
7 min read
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number
Given an array arr[] of size N containing strings, the task is to count the number of strings having the sum of ASCII (American Standard Code for Information Interchange) values of characters equal to an Armstrong Number number or a Prime Number. Examples: Input: arr[] = {"hello", "nace"}Output:Number of Armstrong Strings are: 1Number of Prime Stri
12 min read
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read