Skip to content

Instantly share code, notes, and snippets.

@codersantosh
Forked from dsheiko/strtr.js
Created September 24, 2015 08:53
Show Gist options
  • Select an option

  • Save codersantosh/76544eefb45b68f2ad66 to your computer and use it in GitHub Desktop.

Select an option

Save codersantosh/76544eefb45b68f2ad66 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
* @license MIT
* @copyright (c) Dmitry Sheiko http://dsheiko.com
**/
String.prototype.strtr = function (replacePairs) {
"use strict";
var str = this.toString(), key, re;
for (key in replacePairs) {
if (replacePairs.hasOwnProperty(key)) {
re = new RegExp(key, "g");
str = str.replace(re, replacePairs[key]);
}
}
return str;
}
// Test
console.log("hi {palceholder}, I said hello".strtr({
"{palceholder}" : "Molly",
"hello" : "grüß dich"
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment