var str = "test((name1))testdfe((name2))"; str = str.replace(/\(\(([\w-]+)\)\)/g, function(matches, id) { var elem = document.getElementById(id); return elem ? '((' + elem.innerHTML + '))' : matches; });