Skip to content

Instantly share code, notes, and snippets.

@unnamedfeeling
Forked from dsheiko/strtr.js
Created May 17, 2019 11:26
Show Gist options
  • Save unnamedfeeling/deb41d0d508f9ed5e78d5ac29bfaa6d1 to your computer and use it in GitHub Desktop.
Save unnamedfeeling/deb41d0d508f9ed5e78d5ac29bfaa6d1 to your computer and use it in GitHub Desktop.
Java-script strtr — translate characters or replace substrings
/**
* strtr() for JavaScript
* Translate characters or replace substrings
*
* @author Dmitry Sheiko
* @version strtr.js, v 1.0.1
* @license MIT
* @copyright (c) Dmitry Sheiko http://dsheiko.com
**/
String.prototype.strtr = function ( dic ) {
const str = this.toString(),
makeToken = ( inx ) => `{{###~${ inx }~###}}`,
tokens = Object.keys( dic )
.map( ( key, inx ) => ({
key,
val: dic[ key ],
token: makeToken( inx )
})),
tokenizedStr = tokens.reduce(( carry, entry ) =>
carry.replace( entry.key, entry.token ), str );
return tokens.reduce(( carry, entry ) =>
carry.replace( entry.token, entry.val ), tokenizedStr );
};
// Test
console.log("{palceholder}, I said hello".strtr({
"{palceholder}" : "Molly",
"hello" : "grüß dich"
}));
console.log("{palceholder}, I said hello".strtr({
"{palceholder}" : "hello",
"hello" : "grüß dich"
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment