Skip to content

Instantly share code, notes, and snippets.

@dwhieb
Last active February 1, 2018 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwhieb/d0469524bbf9b47b375540543a376674 to your computer and use it in GitHub Desktop.
Save dwhieb/d0469524bbf9b47b375540543a376674 to your computer and use it in GitHub Desktop.
An intermediate transliteration function that handles substrings during substitution but not other edge cases
// An intermediate transliteration function that handles substrings
// but does not handle other edge cases
const sortedTransliterate = (string = '', substitutions = {}) => {
// save the string to a new variable for readability
let str = string;
// get the list of substitutions
Object.entries(substitutions)
// sort the substitutions by longest string (avoids the substring problem)
.sort(([a], [b]) => b.length - a.length)
// for each substitution...
.forEach(([input, replacement]) => {
// create a regular expression that searches globally for the string to replace
const regexp = new RegExp(input, 'gu');
// then replace all matched instances of the regular expression with the new string
str = str.replace(regexp, replacement);
});
// return the string with the substitutions made
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment