how to get uri segment in js

How to Get URI Segment in JS

URI stands for Uniform Resource Identifier. It is a string of characters that identifies a name or a resource on the internet. Sometimes, you may need to get a specific segment of the URI in your JavaScript code. Here are a few ways to do it:

Using window.location.href Property

You can use the window.location.href property to get the complete URI of the current page. Then, you can split it into an array of segments using the split() method and get the desired segment by its index.


// Get the URI segment at index 2
var uriSegments = window.location.href.split('/');
var segment = uriSegments[2];
console.log(segment);

Using RegExp Object

You can also use the RegExp object to match a specific pattern in the URI and extract the desired segment. Here is an example:


// Get the URI segment at index 2
var regex = /\/([^\/]+)\/([^\/]+)/;
var match = regex.exec(window.location.href);
var segment = match[2];
console.log(segment);

In this example, we are using a regular expression to match two segments in the URI separated by a slash (/). The exec() method returns an array containing the matched segments. We can then access the desired segment using its index.

Using URLSearchParams Object

If you are working with a URL that contains query parameters, you can use the URLSearchParams object to parse and extract the desired segment. Here is an example:


// Get the value of the "id" parameter in the URL
var searchParams = new URLSearchParams(window.location.search);
var id = searchParams.get('id');
console.log(id);

In this example, we are creating a new URLSearchParams object using the window.location.search property, which contains the query parameters in the URL. We can then use the get() method to extract the value of the desired parameter.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe