HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Remove non ASCII characters from a JavaScript string

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
nonjavascriptfromasciiremovecharactersstring

Problem

If you're converting text from a different character set to ASCII, you might end up with characters that are not ASCII compatible. These characters can cause issues when processing or displaying text.
In order to remove them, you can use a regular expression to match all non-ASCII characters and replace them with an empty string. The regular expression [^\x20-\x7E] matches all characters outside the range of printable ASCII characters (from space to tilde). Then, using String.prototype.replace(), you can remove all matches from the string.

Solution

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');

removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'

Code Snippets

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');

removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'

Context

From 30-seconds-of-code: remove-non-ascii

Revisions (0)

No revisions yet.