Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Last active December 29, 2015 12:39
Show Gist options
  • Save hugowetterberg/7671640 to your computer and use it in GitHub Desktop.
Save hugowetterberg/7671640 to your computer and use it in GitHub Desktop.
var hasLanguage = true;
var lang = {
greeting: 'Hello __name__, welcome to __placeHTML__!'
};
var langReplace = /__([^\s]+)__/g;
var entityReplace = /[<>&]/g;
var entities = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;'
};
function naiveEncode(str) {
return str.replace(entityReplace, function getEntity(character) {
return entities[character];
});
}
function t(key, opts) {
if (!hasLanguage) return key;
var str = lang[key] || (opts ? opts.defaultValue : null);
if (!str) return key;
if (!opts) return str;
return str.replace(langReplace, function valueSubstitution(match, name) {
var isHTML = name.substr(-4) == 'HTML';
if (isHTML) {
name = name.substr(0, name.length-4);
}
var translated = opts[name] || name;
if (!isHTML) {
translated = naiveEncode(translated);
}
return translated;
});
}
console.log(t('greeting', {name: 'Simon', place:'Hässleholm'}));
console.log(t('greeting', {name: 'Simon <script>xss foo</script>', place:'Hässleholm'}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment