Skip to content
the poor coder

how to get uri segment in js

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

// 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:

Text

// 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:

Text

// 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC