开发者

Replacing a small chunk of a larger string

So I've got the following code written to go through every Anchor, get it's href, and if it contains the old address, attempt to replace the old base with the new one. While there's obviously an issue long before this code with the site, i need a quick and dirty solution 开发者_运维百科to this problem, so this code is what I'm going for.

So, the code below doesn't work. .Replace apparantly needs a full match, so it would find "foo" in the sentence "foo is good" but not "foo" in "fooIsGood".

$('a').each(function() {
    var addressSwitch = $(this).attr("href");
    if  (addressSwitch){
        var test = addressSwitch.indexOf("http://www.oldaddress.com");
        if ( test == 0){
            addressSwitch.replace("http://www.oldaddress.com/", "www.newaddress.com");
            $(this).attr("href" , addressSwitch);
            }
        }
});

So, what would work?

Thanks in advance!


.replace() works correctly, but you're not assigning the replaced value, it needs to be:

addressSwitch = addressSwitch.replace("http://www.oldaddress.com/", "www.newaddress.com");

Remember that .replace() doesn't change the original string, it returns a new one with the value replaced.

Remember that .attr() also takes a function, so you could slim your code down to this:

$('a[href^="http://www.oldaddress.com"]').attr("href", function(i, href) {
    return href.replace("http://www.oldaddress.com/", "www.newaddress.com");
});


Switch them both to lowercase for the compare, then use newvalue + substring of the length of the newvalue and onward. e.g.

$('a').each(function() {
    var replacer = "http://www.oldaddress.com";
    var addressSwitch = $(this).attr("href");
    if  (addressSwitch){
        var test = addressSwitch.toLowerCase().indexOf(replacer);
        if ( test == 0){
            addressSwitch = replacer + addressSwitch.subString(replacer.length);
            $(this).attr("href" , addressSwitch);
            }
        }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜