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) {
  // 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
    .replace(/\p{Diacritic}/gu, '')
  const normalizedText = text
    .replace(/\p{Diacritic}/gu, '')
  return normalizedText.includes(normalizedSearchTerm);

const filteredNames = nameList.filter((name) => {
  return textSearch('elenè', name);

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

Leave a Reply

Your email address will not be published. Required fields are marked *