Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Last active July 9, 2023 18:18
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dsheiko/2774533 to your computer and use it in GitHub Desktop.
Save dsheiko/2774533 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.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"
}));
@csimpi
Copy link

csimpi commented May 10, 2017

You will get wrong result if function changes a part, than that part will match with a next key again.
For example:

   "{palceholder}" : "hello",     
    "hello" : "grüß dich"

You will get grüß dich instead of hello in {palceholder}'s place.

@denmedia
Copy link

Dosen't work ((

var str  = '[test]';
var result = str.strtr({'[':'-',']':'-'});

Error: Uncaught SyntaxError: Invalid regular expression: /[/: Unterminated character class

@bolasblack
Copy link

A better version, resolve @csimpi issue:

const escapeRE = require('lodash.escaperegexp')
const strtr = (str, pairs) => {
  const substrs = Object.keys(pairs).map(escapeRE)
  return str.split(RegExp(`(${substrs.join('|')})`))
            .map(part => pairs[part] || part)
            .join('')
}

@dsheiko
Copy link
Author

dsheiko commented Dec 6, 2018

Opps, I was not even aware I have comments on that. Sorry, Thank you guys, the mentioned issues are valid. I've just updated the gist with the fix

@SnowyYANG
Copy link

this only replace each pair of words once

@dsheiko
Copy link
Author

dsheiko commented Jan 17, 2022

@SnowyYANG You're right. I updated the snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment