All you need to do is use string replace
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
If you want it to be done depending upon the token, you'd need a little more work:
function replacer(match, p1, string){
// p1 is the first group (\w+)
var stuff = {
dog: "woof",
cat: "meow"
};
return stuff[p1] || "";
};
newString = "A dog says $dog. A cat says $cat.".replace(/\$(\w+)/g, replacer);
results in
"A dog says woof. A cat says meow."
Edit: Actually, if you want to do a kind of string interpolation on global variables, it's also pretty easy, though I wouldn't recommend this. Please don't unless you have a really good reason. And if you say you have a good reason, I probably wouldn't believe you. My first example, where I give a particular dictionary/object to search, is much better. Please don't go about polluting the global namespace just because this works!
var dog ="woof";
var cat = "meow";
function replacer(match, p1, string){
return window[p1] || "";
};
newString = "A dog says $dog. A cat says $cat.".replace(/\$(\w+)/g, replacer);