JavaScript compare strings with accents

Remove/ignore accents/diacritics when comparing strings in JavaScript:


const nameList = ['Hélène', 'Mèle', 'Zoe'];



function textSearch(searchTerm, text) {

  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize

  // normalize() decompose accented characters into their component parts

  // replace() removes the combining diacritical marks

  // This ensures that the search term and text are compared in a way that ignores accents and diacritical marks

  // Old approach: .replace(/[\u0300-\u036f]/g, '')

  const normalizedSearchTerm = searchTerm

    .normalize('NFD')

    .replace(/\p{Diacritic}/gu, '')

    .toLowerCase()

    .trim();

  const normalizedText = text

    .normalize('NFD')

    .replace(/\p{Diacritic}/gu, '')

    .toLowerCase()

    .trim();

  return normalizedText.includes(normalizedSearchTerm);

}



const filteredNames = nameList.filter((name) => {

  return textSearch('elenè', name);

});



console.log(filteredNames); // Returns ["Hélène"]

Leave a Comment