Retrieve details about the current document location by using the Window.location read-only property.
javascript Window.location
var url1 = window.location; //returns the url as an object
var url2 = window.location.href; //returns the url string
var url3 = window.location.pathname; //returns the url path
Utilize the split() method to divide a String object into an array of strings by separating substrings.
javascript .split()
To split the URL, use .split("-")
. For example, if all pages are in the format /page-2
, this will return an object {"page","2"}
var pathSplit = url3.split("-"); //returns {"page","2"} from page-2
The slice() method isolates a part of a string and gives a new string.
javascript .slice()
If your path ends with a /
, you can utilize .slice() to remove the last character.
var pathSplice = url3.slice(0,-1); //returns /page-2 from /page-2/
var pathSplit = pathSplice.split("-"); //returns {"/page","2"} from /page-2
To extract the page number 2
, access the index 1
of the pathSplit
object, parse the number as an integer, and perform necessary calculations for desired pages.
var pageNum = parseInt(pathSplit[1]);
var prevPage = 0,
nextPage = 0;
if(isNaN(pageNum) === false){
prevPage = pageNum - 1; //returns 1 from 2
nextPage = pageNum + 1; //returns 3 from 2
}
[Element.setAttribute()]Modify the value of an attribute on a specified element. Update or add attributes as needed.
javascript .setAttribute()
To update anchor tags <a></a>
, follow these steps
var prevLink = document.querySelector(".prev-link");
var nextLink = document.querySelector(".next-link");
prevLink.setAttribute("href", "/page-" + prevPage.toString());
nextLink.setAttribute("href", "/page-" + nextPage.toString());
REMINDER: Remember to assign classes or IDs to previous and next page links.