Last active
July 9, 2023 18:18
-
-
Save dsheiko/2774533 to your computer and use it in GitHub Desktop.
Java-script strtr — translate characters or replace substrings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* strtr() for JavaScript | |
* Translate characters or replace substrings | |
* | |
* @author Dmitry Sheiko | |
* @version strtr.js, v 1.0.2 | |
* @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( new RegExp( entry.key, "g" ), entry.token ), str ); | |
return tokens.reduce(( carry, entry ) => | |
carry.replace( new RegExp( entry.token, "g" ), 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
this only replace each pair of words once