Shrtfrm:
"I love :octocat: beach and you do :joy: not like it".split(":").map((el,i)=>i%2===0?el:{"octocat":"hello","joy":"test"}[el]||el).join("");
Simply split, replace and join again.
http://jsbin.com/moxexilica/edit?console
Explanation:
.split(":")
//returns: ["I love ","octocat"," beach and you do ","joy"," not like it"]
.map((el,i)=>i%2===0?el
//leave the strings outside (indexes 0,2,4) as they are
:el{"octocat":"hello","joy":"test"}[el]
//replace the others (indexes 1,3) with the value in the object so:
// octocat => hello
//joy => test
||el
//if it does not exist e. g. ':test:' fall back to 'test'
//now weve got:
//["I love ","hello"," beach and you do ","test"," not like it"]
.join("")
//a string
Extracted to a function:
function replace(str,replacer){
return str.split(":").map((el,i)=>i%2===0?el:replacer[el]||el).join("");
}
So you can do:
alert(replace("I love :octocat: beach and you do :joy: not like it", {octocat:"manly",joy:"not"}));
With images:
document.body.innerHTML=replace(document.body.innerHTML, {octocat:"<img src='octocat.png' />",joy:"<img src='joy.png' />"});
Note that ":" is not a good delemiter. You may use a more uncommon one like %% or !! ...