<script type="text/javascript">
var haystackText = document.getElementById("navigation").innerHTML;
var matchText = '<a href="http://mydomain.co/?feed=rss">Subscribe to RSS</a>';
var replacementText = '<ul><li>Some Other Thing Here</li></ul>';
var replaced = haystackText.replace(matchText, replacementText);
document.getElementById("navigation").innerHTML = replaced;
</script>
I’m attempting to try and replace a string of HTML code to be something else. I cannot edit the code directly, so I’m using Javascript to alter the code.
If I use the above method Matching Text on a regular string, such as just ‘Subscribe to RSS’, I can replace it fine. However, once I try to replace an HTML string, the code ‘fails’.
Also, what if the HTML I wish to replace contains line breaks? How would I search for that?
<ul><li>\n</li></ul>
??
What should I be using or doing instead of this? Or am I just missing a small step? I did search around here, but maybe my keywords for the search weren’t optimal to find a result that fit my situation…
Edit: Gonna mention, I’m writing this script in the footer of my page, well after the text I wish to replace, so it’s not an issue of the script being written before what I want to overwrite to appear. 🙂
Currently you are using
String.replace(substring, replacement)that will search for an exact match of thesubstringand replace it with thereplacemente.g.The problem with exact matches is that it doesn’t allow anything else but exact matches.
To solve the problem, you’ll have to start to use regular expressions. When using regular expression you have to be aware of
?,/, and\that need to escaped\?,\/,\\\s+for [1..n] white-space characters and\s*for [0..n] white-space characters.To use regular expression instead of substring matching you just need to change
String.replace("substring", "replacement")toString.replace(/regexp/, "replacement")e.g.