DEV Community

Cover image for How to remove accent marks in a string using vanilla Javascript
LuisPa
LuisPa

Posted on

2

How to remove accent marks in a string using vanilla Javascript

In JS is quite of easy to replace chars by using str.replace for example, but, what happens when you want to remove accent marks?

I'm a native Spanish speaker, so this could be helpful if you need to handle some Spanish words.

This tiny post will build an example on how to make a slug from a Spanish sentences strings.

The code

// Input example
const spanishSentences = [
  "teléfono",
  "árbol",
  "colibrí",
  "cómpramelo",
  "Mandó una carta",
  "Qué grande es ese perro"
];

// Function definition
function createSlug(input){
  return input
    .toLowerCase()
    .trim()
    .replace(/[\s_-]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "");
}

// Usage
const output = spanishSentences.map(createSlug);
console.log(output);
// Output:
/*
[
  "telefono", 
  "arbol", 
  "colibri", 
  "compramelo", 
  "mando-una-carta", 
  "que-grande-es-ese-perro"
]
*/
Enter fullscreen mode Exit fullscreen mode

You can test it in this JS Bin

And that's it, happy coding!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs