Search code examples
javascriptjqueryregexhref

Replace href with jQuery, regular expression


I have a bunch of href links that need to be replaced:

<a id="link" href="http://localhost:8091/tabid/99/catid/8/page1.aspx">Page1</a>
<a id="link" href="http://localhost:8091/tabid/98/catid/8/page1.aspx">Page1</a>
<a id="link" href="http://localhost:8091/tabid/97/catid/8/page1.aspx">Page1</a>

The href should be changed to: "http://localhost:8091/tabid/1/catid/8/page1.aspx"

By searching I found:

$(document).ready(function () {
    $("#link").each(function () {
        this.href = this.href.replace("99", "1");
    });
});

This should do the job. However, it only replaces one of the links. Could anyone help me with the regular expression here? I need to change all the numbers in tabid/**/catid to "1".


Solution

  • First, change id to class. Second, make this change:

    this.href = this.href.replace(/tabid\/\d+/i, '/tabid/1');
    

    Now it only replaces the numbers after tabid, not just any number anywhere in the string.