I’m trying to replace text inside an HTML string with Javascript.
The tricky part is that I need to replace the text only if it isn’t inside a tag (meaning it’s not part of an attribute):
var html_str = '<div>hi blah blah<img src="img.jpg" alt="say hi" /><a href="link_hi.php">hi!</a></div>';
In this example, after I do html_str.replace("hi","hello"); I want to replace only the text inside the div and a tags, avoiding the <img alt=".." or the href="....
Some more info:
html_str = document.body.innerHTML;, therefore the elements are unknown. The example above is only an example.- Regex are more than welcome.
- The
hiandhellovalues are inside varaibles, meaning the actual replace is like so:html_str.replace(var1,var2);
The REAL code is this:
var html_str = document.body.innerHTML;
var replaced_txt = "hi";
var replace_with = "hello";
var replaced_html = html_str.replace(replaced_txt,replace_with);
I hope I explained myself well.
Thanks in advance.
This maybe?
http://jsfiddle.net/G8fYq/4/ (uses document.body directly)
If you want to make the changes visible immediately then you could also pass
document.bodyand forget about the wholecontainerstuff.Update to allow for multiple replacements in one run.
You could also try XPath in javascript, though the following solution will not work in IE.