How to change the current URL in javascript?

后端 未结 4 888
名媛妹妹
名媛妹妹 2020-12-28 13:30

On my website:

http://mywebsite.com/1.html

I want to use the

window.location.pathname

to get the last pa

相关标签:
4条回答
  • 2020-12-28 13:44

    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.

    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();
    

    Demo here: http://jsfiddle.net/jfriend00/3VPEq/

    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.

    0 讨论(0)
  • 2020-12-28 13:49

    This is more robust:

    mi = location.href.split(/(\d+)/);
    no = mi.length - 2;
    os = mi[no];
    mi[no]++;
    if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
    location.href = mi.join('');
    

    When the URL has multiple numbers, it will change the last one:

    http://mywebsite.com/8815/1.html
    

    It supports numbers with leading zeros:

    http://mywebsite.com/0001.html
    

    Example

    0 讨论(0)
  • 2020-12-28 13:55

    Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

    function nextImage (){
    url = url + 1;  
    location.href='http://mywebsite.com/' + url+'.html';
    }
    
    0 讨论(0)
  • 2020-12-28 13:57

    What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

    Why not do something like this:

    var url = 'http://mywebsite.com/1.html';
    var pageNum = parseInt( url.split("/").pop(),10 );
    var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
    

    nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

    0 讨论(0)
提交回复
热议问题