开发者

Link detect and replace the other,in js

开发者 https://www.devze.com 2023-02-10 15:07 出处:网络
Hello I wonder how Replace automatically links on my site that start with: http://site.com/00000/ to: http://site.com/11111/

Hello I wonder how Replace automatically links on my site that start with:

http://site.com/00000/

to:

http://site.com/11111/

开发者_StackOverflow社区

detects> replaces


CSS3 attribute "starts with" selectors help you there (and jQuery supports them on all of the browsers it supports — with native features if possible, for speed). Then just use an each loop and update the href property of the raw a element:

$("a[href^='http://site.com/00000/']").each(function() {
    this.href = "http://site.com/11111/" + this.href.substring(21);
});


You can use jQuerys .attr() method. You don't need to explicitly invoke .each(), jQuery will take care of you if your selector hits multiple nodes. Since version 1.4.1, .attr() like many other setters, takes a function as argument. This function gets the index and the actual value passed in. Whatever you return from this callback is going to be the new value.

$(document).ready(function () { 
    $('a').attr('href', function(_, href) {
         return href.replace('246619', '262257');
    });
});

Demo: http://www.jsfiddle.net/qR2NU/

Reference: .attr()


<script type="text/javascript">
    $(document).ready(function () { 
        var urlContain = new RegExp('Detect Value Here');
        $('a').each(function () { 
            var href = this.getAttribute('href').replace(urlContain, 'Replacement here');
            $(this).attr('href', href);
        });
    });
</script>


This code loops through every link on the page that has a href attribute once the DOM has loaded and performs the required replace:

$(function() {
  $('a').each(function() {
    var href = $(this).attr('href');
    if (href !== undefined) {
      href = href.replace(/246619/g, '262257');
    }
    $(this).attr('href', href);
  });
});

The above relies on jQuery but judging by the tags you used for your question, you are already using it.


Untested:

$("a[href^=http://site.com/00000/]").each(function() {
  this.href = "http://site.com/11111/" + this.href.substr("http://site.com/00000/".length");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消