index.js 886 B

123456789101112131415161718192021222324252627282930313233
  1. import escapeStringRegexp from 'escape-string-regexp';
  2. import builtinReplacements from './replacements.js';
  3. const doCustomReplacements = (string, replacements) => {
  4. for (const [key, value] of replacements) {
  5. // TODO: Use `String#replaceAll()` when targeting Node.js 16.
  6. string = string.replace(new RegExp(escapeStringRegexp(key), 'g'), value);
  7. }
  8. return string;
  9. };
  10. export default function transliterate(string, options) {
  11. if (typeof string !== 'string') {
  12. throw new TypeError(`Expected a string, got \`${typeof string}\``);
  13. }
  14. options = {
  15. customReplacements: [],
  16. ...options
  17. };
  18. const customReplacements = new Map([
  19. ...builtinReplacements,
  20. ...options.customReplacements
  21. ]);
  22. string = string.normalize();
  23. string = doCustomReplacements(string, customReplacements);
  24. string = string.normalize('NFD').replace(/\p{Diacritic}/gu, '').normalize();
  25. return string;
  26. }