Home > Back-end >  Javascript replace & changing sting from a vriable
Javascript replace & changing sting from a vriable

Time:12-25

I have a URL https://example.com/fullimg.php?eid=1&pgno=&pdate=2022-12-24,

I want to create a next and previous button. If the user clicks on the next button he will redirect to pgno=1 means the next page. If he clicks on the next button again he will be redirected to pgno=2 and so on if he clicks next again he will be redirected to pgno=3 here the pdate is dynamic and changes every day.

I have tried this

      let url = window.location.href;
      if (url.includes("pgno=")) {
        url = url.replace("pgno=", "pgno=2");
      } else if (url.includes("pgno=2")) {
        url = url.replace("pgno=", "pgno=3");
      }
      console.log(url);
      window.location.replace(url);

Also I have tried this

      let url = window.location.href;
      if (url.includes("pgno=")) {
        url = url.replace("pgno=", "pgno=2");
      } 
      if (url.includes("pgno=2")) {
        url = url.replace("pgno=", "pgno=3");
      }
      console.log(url);
      window.location.replace(url);

For both it's only executing first condition not the 2nd one. After clicking on the next button it's going to pgno=2 but after that when I am clicking next it's still reloading and redirecting to pgno=2

How can I solve it?

I have solved it, thanks to @Unmitigated

this is the function,

    function Next2() {
      let params = new URLSearchParams(location.search);
      // get the value of pgno
      let pgno =  params.get('pgno');
      // check if pgno is less than or equal to 12
      if (pgno <= 11) {
        // go to next page
        params.set('pgno', pgno   1);
        location.search = params;
      }
    }

And here is the previous function

    function Prev1() {
      let params = new URLSearchParams(location.search);
      // get the value of pgno
      let pgno =  params.get('pgno');
      // check if pgno is greater than 1
      if (pgno > 1) {
        // go to previous page
        params.set('pgno', pgno - 1);
        location.search = params;
      }
    }

CodePudding user response:

Use URLSearchParams to facilitate handling query strings.

let params = new URLSearchParams(location.search);
// go to next page
params.set('pgno',  params.get('pgno')   1);
location.search = params;
  • Related