-
-
Save hugowetterberg/7671640 to your computer and use it in GitHub Desktop.
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
var hasLanguage = true; | |
var lang = { | |
greeting: 'Hello __name__, welcome to __placeHTML__!' | |
}; | |
var langReplace = /__([^\s]+)__/g; | |
var entityReplace = /[<>&]/g; | |
var entities = { | |
'<': '<', | |
'>': '>', | |
'&': '&' | |
}; | |
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