Skip to content

Instantly share code, notes, and snippets.

@cpsubrian
Created October 23, 2012 23:32
Show Gist options
  • Save cpsubrian/3942527 to your computer and use it in GitHub Desktop.
Save cpsubrian/3942527 to your computer and use it in GitHub Desktop.
Replace named tokens in a string.
var input = 'Hello, :name.first :name.last! :greeting';
function tokenReplace(str, values) {
return str.replace(/:([\w.]+)/g, function (token, name) {
return name.split('.').reduce(function (value, part) {
return value[part] || null;
}, values) || token;
});
}
console.log(tokenReplace(input, {
name: {
first: 'Brian',
last: 'Link'
},
greeting: 'How are you doing?'
}));
// Should output: "Hello, Brian Link! How are you doing?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment