Skip to content

Instantly share code, notes, and snippets.

@renz45
Last active August 29, 2015 14:22
Show Gist options
  • Save renz45/bc885afb571e4bc38021 to your computer and use it in GitHub Desktop.
Save renz45/bc885afb571e4bc38021 to your computer and use it in GitHub Desktop.
I came up to a problem the other day where I had to do a sort of token replacement in html without removing/recompiling the html nodes. I was working in angular, so data attached to html nodes needed to be preserved in this process. Below is my initial attempt, which seems to work at a glance.
<div id="test-el">
<div>some testing text blah</div>
<div>some testing <span>%replace%test span</span> text blah</div>
<p>something %replace% something blah</p>
</div>
<div id="control">
<div>some testing text blah</div>
<div>some testing <span>%replace%test span</span> text blah</div>
<p>something %replace% something blah</p>
</div>
<script>
var el = document.getElementById('test-el')
var replacePatternInHtml = function(htmlEl, pattern, replacement) {
var replaceToken = function(text) {
var newSpan
var str = text.textContent
var strArr = str.split(pattern)
var newArr = [document.createTextNode(strArr.shift())]
while(strArr[0]){
newSpan = document.createElement('span');
newSpan.innerHTML = replacement
newArr.push(newSpan)
newArr.push(document.createTextNode(strArr.shift()))
}
return newArr;
}
var searchAndReplace = function(el) {
var item, newItems;
for(var i=0, l=el.childNodes.length; i < l; i++) {
item = el.childNodes[i]
if(item.nodeType == 3) {
newItems = replaceToken(item)
for(var ii=0, ll=newItems.length; ii < ll; ii++) {
el.insertBefore(newItems[ii], item)
}
el.removeChild(item)
} else {
searchAndReplace(item)
}
}
}
searchAndReplace(htmlEl)
}
replacePatternInHtml(el, new RegExp("%replace%"), "[TEST REPLACE]")
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment