Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById replace HTML

<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. :)

like image 229
Kojichan Avatar asked Nov 04 '25 23:11

Kojichan


1 Answers

Currently you are using String.replace(substring, replacement) that will search for an exact match of the substring and replace it with the replacement e.g.

"Hello world".replace("world", "Kojichan") => "Hello Kojichan"

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

  • special characters such as ?, /, and \ that need to escaped \?, \/, \\
  • multiline mode /regexp/m
  • global matching if you want to replace more than one instance of the expression /regexp/g
  • closures for allowing multiple instances of white space \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") to String.replace(/regexp/, "replacement") e.g.

"Hello world".replace(/world/, "Kojichan") => "Hello Kojichan"
like image 68
Aleksi Yrttiaho Avatar answered Nov 06 '25 14:11

Aleksi Yrttiaho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!