Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 17th, 2012  |  syntax: None  |  size: 1.73 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. javascript - replacing text not between in attributes
  2. var html_str = '<div>hi blah blah<img src="img.jpg" alt="say hi" /><a href="link_hi.php">hi!</a></div>';
  3.        
  4. var html_str = document.body.innerHTML;
  5. var replaced_txt = "hi";
  6. var replace_with = "hello";
  7. var replaced_html = html_str.replace(replaced_txt,replace_with);
  8.        
  9. var obj = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what's up'}; // This may contain a lot more data
  10.  
  11. (function helper(parent, replacements) {
  12.   [].slice.call(parent.childNodes, 0).forEach(function (child) {
  13.     if (child.nodeType == Node.TEXT_NODE) {
  14.       for (var from in replacements) {
  15.         child.nodeValue = child.nodeValue.replace(from, replacements[from]);
  16.       }
  17.     }
  18.     else {
  19.       helper(child, replacements);
  20.     }
  21.   });
  22. }(document.body, obj));
  23.        
  24. var
  25.   replacements = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what's up'},
  26.   elements = document.evaluate('//text()', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
  27.   i = 0,
  28.   textNode, from;
  29.  
  30. for (; i < elements.snapshotLength; i += 1) {
  31.   textNode = elements.snapshotItem(i);
  32.  
  33.   for (from in replacements) {
  34.     if (replacements.hasOwnProperty(from)) {
  35.       textNode.nodeValue = textNode.nodeValue.replace(from, replacements[from]);
  36.     }
  37.   }
  38. }
  39.        
  40. var str = '<div>hi blah blah<img src="img.jpg" alt="say hi" /><a href="link_hi.php">hi!</a></div>',
  41.     rx = new RegExp('(>[^>]*)' + 'hi' + '([^>=]*<)', 'g');
  42.  
  43. str = str.replace(rx, '$1hello$2');
  44.        
  45. var $body=$('body'); //create a jquery object of the DOM body
  46. $body.find('*').each(function(index) // foreach element inside the body
  47. {
  48.    $(this).text(  $(this).text().replace('hi','hello')  ); //replace only the text
  49. });