How to search ignoring accents in JavaScript
In this article you will learn how to create a search ignoring accents in JavaScript – using native features of the language and in a simple way

Hey you programmer, ok? Let’s learn how to create a search resource with JavaScript!
The main idea in this concept is to use a regular expression to remove all accents
Because it’s the easiest way to work with strings, in order to manipulate something in them
If we chose another approach like a loop for or if condition structures, the code could get unnecessarily too complex and not very maintainable.
The regular expression is characterized by the following statement:
// without object instance let re = /\w+/; // with object instantiation let re = new RegExp('\\w+');
Both approaches will have the same final result, however we will choose the objectless one because the syntax is simpler
So the next step is to use the replace method so we can replace all accents in unaccented characters
See the full function on how to replace special characters:
function removeSpecials(text) { text = text.replace(/[ÀÁ ÃÄÅ]/,"A"); text = text.replace(/[àáâãäå]/,"a"); text = text.replace(/[ÈÉÊË]/,"E"); text = text.replace(/[Ç]/,"C"); text = text.replace(/[ç]/,"c"); return text.replace(/[^a-z0-9]/gi,''); } let words = [ 'acentuação', 'maçã', 'crachá', 'água' ]; for(let i = 0; i < words.length; i++) { console.log(removeSpecials(words[i])); }
The return of this array will be:
"acentuacao" "maca" "cracha" "agua"
Now we can do our tests on the word without accent if it matches the word in the list
See the full example:
function removeSpecials(text) { text = text.replace(/[ÀÁ ÃÄÅ]/,"A"); text = text.replace(/[àáâãäå]/,"a"); text = text.replace(/[ÈÉÊË]/,"E"); text = text.replace(/[Ç]/,"C"); text = text.replace(/[ç]/,"c"); return text.replace(/[^a-z0-9]/gi,''); } let words = [ 'acentuação', 'maçã', 'crachá', 'água' ]; let wordToFind = 'cracha'; for(let i = 0; i < words.length; i++) { if(removeSpecials(word[i]) === wordToFind ) { console.log(`Found ${palavras[i]}!`); } }
See how simple it is!
Conclusion
In this article we learned how to create a search ignoring accents in JavaScript
The first step is to remove all special characters via regex
Then we just need to make the comparison between the word we want to find and also the set of words we are looking for
Want to learn more about JavaScript and web development? Click here!