Search code examples
javascripthtmlhref

javascript for changing link's href in html page


My problem is the following:

I have a page with many links Some of them have a specific pattern :

http://www.example.com/.../?parameter1=...&parameter2=PARAMETER2

What i want to do is to change these links' href to the value of the parameter2 using JavaScript. For example if i have a link like :

<a href="http://www.example.com/.../?parameter1=...&parameter2=PARAMETER2">text here</a> 

what i want to do after the script runs is to have a link like this:

<a href="PARAMETER2">text here</a>

Any suggestion would be truly appreciated!!! Thank you all in advance!!!


Solution

  • If you are using jquery

    then use the following code

    $(function() {
      $("a[href^='www.example.com']").each(function(){
        var ele = $(this);
        var href = ele.attr("href");console.log(href);
        var index = href.lastIndexOf("parameter2");
        var param_2 = href.substring((index + 11));
        ele.attr("href", param_2);
      });
    });