How do I remove accents and replace spaces with: _?

Asked

Viewed 274 times

-2

I got this guy:

this.logger.logButton(`${this.selectedRadio.title}_${this.selectedRadio.cidade}`, { pram: 'paramValue' });

his return comes for example: Rádio Mix_São Paulo I wish the return was: Radio_Mix_Sao_Paulo

How do I do this in angular/typescript?

  • This can help you on the score withdrawal. https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript. In the space part you can take the variable and make a replace. _variavel.replace(' ', '_').

1 answer

4

Use the replace method by passing regular expressions

const palavra = 'Rádio Mix_São Paulo';

const semEspacos = palavra.replace(/ /g, '_');
console.log(semEspacos);

const semAcentos = semEspacos.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
console.log(semAcentos);

The hardest part to understand here is probably the removing of accents part. First the method normalize converts the string, transforming accented characters into two separate characters, the letter and the accent. Then the regular expression converts all characters between code 300 and 36f of UTF-8 format (which includes accents) into an empty string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.