I need to update href value using jquery

后端 未结 7 442
南笙
南笙 2021-01-15 02:35

I need to update href value thorughout the page using jquery. Say href=\"http://www.google.com?gsec=account\" should be changed to href=\"http://account.google.com?gsec=acco

7条回答
  •  -上瘾入骨i
    2021-01-15 02:41

    This should hopefully provide a pretty full solution to your problem (as best I can interpret it, anyway):

    $(function() {
      $('a').each(function() {
        var $this = $(this),
          href = $this.attr('href');
        var res = href.match(/(.*?)(www)(\.google\.com.*?)([?&]gsec=)([^&]+)(.*)/);
        if (null != res) {
          // remove the "full match" entry
          res = res.slice(1);
          // replace www match with account match
          res[1] = res[4];
          // update the href attribute
          $this.attr('href', res.join(''))
        }
      });
    });
    


    edit: If "account" is a static value, then this will work as well:

    $(function() {
      $('a').each(function() {
        var $this = $(this),
          href = $this.attr('href');
        var res = href.match(/(.*?\/\/)(www)(\.google\.com.*?)([?&]gsec=account)(&?.*)/);
        if (null != res) {
          // remove the "full match" entry
          res = res.slice(1);
          // replace www match with account match
          res[1] = 'account';
          // update the href attribute
          $this.attr('href', res.join(''))
        }
      });
    });
    

    Please note that these solutions assume that there may be other variations in the URL, such as http/https and other query string variables.

提交回复
热议问题