Search code examples
javascripthtmlhyperlinkip

change ip inside link using javascript


so my goal is to change ip address in link with user's current ip. This is script for returing current user ip address.

<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
  var userip;
  document.write(userip); // write to html
</script>

Link example:

www.mysite.com/data/uploads/file.mp3?e=14512&ip=IPHERE&amp=blbablaba&next=fasfass

How can I make to write user's ip to "IPHERE" place and link will look like:

<a href="www.mysite.com/data/uploads/file.mp3?e=14512&ip=123.123.123.123&amp=blbablaba&next=fasfass">link with ip</a>

without changing anything else.

Thanks.


Solution

  • You can search for all a tags and replace href:

    [].slice.call(document.querySelectorAll('a')).forEach(function(a) {
        a.href = a.href.replace(/IPHERE/g, userip);
    });