
Untitled
By: a guest on
May 17th, 2012 | syntax:
None | size: 1.73 KB | hits: 10 | expires: Never
javascript - replacing text not between in attributes
var html_str = '<div>hi blah blah<img src="img.jpg" alt="say hi" /><a href="link_hi.php">hi!</a></div>';
var html_str = document.body.innerHTML;
var replaced_txt = "hi";
var replace_with = "hello";
var replaced_html = html_str.replace(replaced_txt,replace_with);
var obj = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what's up'}; // This may contain a lot more data
(function helper(parent, replacements) {
[].slice.call(parent.childNodes, 0).forEach(function (child) {
if (child.nodeType == Node.TEXT_NODE) {
for (var from in replacements) {
child.nodeValue = child.nodeValue.replace(from, replacements[from]);
}
}
else {
helper(child, replacements);
}
});
}(document.body, obj));
var
replacements = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what's up'},
elements = document.evaluate('//text()', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
i = 0,
textNode, from;
for (; i < elements.snapshotLength; i += 1) {
textNode = elements.snapshotItem(i);
for (from in replacements) {
if (replacements.hasOwnProperty(from)) {
textNode.nodeValue = textNode.nodeValue.replace(from, replacements[from]);
}
}
}
var str = '<div>hi blah blah<img src="img.jpg" alt="say hi" /><a href="link_hi.php">hi!</a></div>',
rx = new RegExp('(>[^>]*)' + 'hi' + '([^>=]*<)', 'g');
str = str.replace(rx, '$1hello$2');
var $body=$('body'); //create a jquery object of the DOM body
$body.find('*').each(function(index) // foreach element inside the body
{
$(this).text( $(this).text().replace('hi','hello') ); //replace only the text
});