While testing a web page or the site, there can be a requirement to extract the URL of different web pages on the developer’s end. For instance, storing the URL corresponding to each web page in the relevant code to access them or utilize the added functionalities in the future. In such case scenarios, getting the portion of the URL path is convenient for managing the resources effectively.
- “host” and “pathname” properties.
- “slice()” and “split()” methods.
The “location.host” property returns the IP address and port of a URL. The “pathname” property gives the pathname of a URL. These properties can be utilized to split the IP address and path name in the URL and fetch them separately.
Overview the below-given demonstration:
let a = window.location.host
let b = window.location.pathname
console.log(‘The first portion of the URL is : ‘, a);
console.log(‘The second portion of the URL is : ‘, b);
In the above demonstration:
- Firstly, apply the “host” property to fetch the IP address.
- Likewise, get the path name contained in the URL via the “pathname” property
- Lastly, display the fetched portions from the URL on the console.
In the above output, it can be observed that the IP address and the path have been fetched separately from the redirected URL.
The “split()” method splits a string into a substring array based on the parameters and the “slice()” method extracts a part of the string. These methods can be applied along with the “pathname” property to fetch the path name from the URL based on the parameter of the applied methods.
In the given syntax:
- “separator” points to the string that needs to be used for splitting.
- “limit” refers to the integer that limits the number of splits.
In the above syntax:
- “start” and “end” indicate the start and end positions, respectively.
Let’s go through the following lines of code to understand the concept clearly:
let myLink = new URL(“http://www.google.com/home/section1”);
let myPortion = myLink.pathname.split(‘/’).slice(1);
console.log(‘The portions in the URL are : ‘, myPortion);
In the above code snippet:
- Firstly, create the new URL object using the “new” keyword and the “URL()” constructor, respectively to represent the specified URL.
- In the next step, associate the “split()” and “slice()” methods with the “pathname” property such that the path name is extracted from the specified URL based on the given separator and limit, respectively.
- Finally, display the portions of the path name in the URL as an array on the console.
In the output, it can be noticed that the portions of the path from the URL are returned as an array.