且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在javascript中更改当前URL?

更新时间:2022-04-27 09:26:44

您的示例无效,因为您尝试将1添加到如下所示的字符串:1.html。这只会让你得到这个1.html1,这不是你想要的。您必须隔离字符串的数字部分,然后将其转换为实际数字,然后才能对其进行数学运算。在获得实际数字后,您可以增加其值,然后将其与字符串的其余部分合并。

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

您可以使用这样的自定义替换函数隔离原始URL的各个部分并用增加的数字替换该数字:

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

然后你可以这样打电话:

You can then call it like this:

window.location.href = nextImage();

在这里演示: http://jsfiddle.net/jfriend00/3VPEq/

这适用于任何以一系列数字后跟.html结尾的URL如果你需要一个稍微不同的URL表单,你可以调整正则表达式。

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.