For this type of string manipulation, as a starting point, you could take advantage of using a powerful feature of the String.prototype.replace function, using its callback function:
function replaceTokens(str, replacement) {
return str.replace(/\%([^%]+)\%/g, function (string, match) {
return replacement[match];
});
}
replaceTokens("move %mouseX%+1 %mouseY%+1", {mouseX: 100, mouseY: 200});
// returns "move 100+1 200+1"
replaceTokens("%foo% %bar%!!!", {foo: 'Hello', bar: 'World'});
// returns Hello World!!!
replaceTokens("I'm %name%, and I %action% %place%", {name: 'CMS',
action: 'love',
place:'StackOverflow'
}); // "I'm CMS, and I love StackOverflow"
That is only a simple example about the sort of things that you are able to do with this technique. This small function will make you able to do multiple %token% replacements in one step.
Recommended article: