Make exception when replacing diacritics with regular characters

Viewed 53

Trying to make an exception to all characters that have been converted to regular letters.

txtValue.normalize('NFD').replace(/[\u0300-\u036f]/g, '');

As you can see, I replace all the special characters for normal letters, but now I would like to add an exception for the char "ç" and it's capital equivalent "Ç", which are u00e7 and u00c7 respectively.

1 Answers

The only simple way I see is not optimized but do the job properly :

const text = "Çééé éÇé àç" // test this string
  .replace(/\u00e7/g, '__minC__') // save wanted chars position
  .replace(/\u00c7/g, '__majC__')
  .normalize('NFD') // normalize to prepare diacritic edit
  .replace(/\p{Diacritic}/gu, '') // replace all diacritics
  .replace(/__minC__/g, 'ç') // restore wanted chars
  .replace(/__majC__/g, 'Ç')
  
  console.log(text)

In this case we use \p{Diacritic} from Unicode Property Escapes

Related