Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Replace Accented Characters with their Plain English Counterparts in JavaScript

I was working on this little app that lets you convert any text to a slug. And while working on it, I came across this problem where I had to replace accented characters with their plain English counterparts.

If you’re not aware, accented characters are the characters that have a diacritical mark. For example, é, à, ç, ñ, etc. are accented characters. These characters are used in many languages like French, Spanish, Portuguese, etc.

To replace these accented characters with their plain English counterparts in JavaScript, we can use the normalize() method which is available on the String object.

The normalize() method returns the Unicode Normalization Form of a given string. It accepts a parameter called form which can be one of the following values:

  • NFC - Normalization Form Canonical Composition
  • NFD - Normalization Form Canonical Decomposition
  • NFKC - Normalization Form Compatibility Composition
  • NFKD - Normalization Form Compatibility Decomposition

For our use case, we can use the NFD form which will decompose the accented characters into their plain English counterparts.

For instance, é will be decomposed into e and ´.

Next, we can pass the decomposed string to the replace() method and replace the accented characters with their plain English counterparts like so.

const title = 'My Fiancé';

const nonAccentedTitle = title.normalize('NFD')
                   .replace(/[\u0300-\u036f]/g, '');

console.log(nonAccentedTitle);
// output: My Fiance

As you can tell, we’re using the regex /[\u0300-\u036f]/g to match all the accented characters and replace them with an empty string.

We can even make this into a reusable function like so.

const replaceAccentedCharacters = (str) => {
    return str.normalize('NFD')
              .replace(/[\u0300-\u036f]/g, '');
}

And that’s how you can replace accented characters with their plain English counterparts in JavaScript.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?