EN
JavaScript - get id from URL
5
points
In this article, we would like to show you how to get id from URL using JavaScript.
The id in the URL can be stored in several ways:
- in the path,
- in the name,
- after the question mark in (request parameter).
In all the solutions below, the main concept is to get the number using the regex groups:
(\d+)if the id is a number,([a-z]+)if the id is a text.
ID in the path
Number based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\/(\d+)\/.*/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items/123/item-name-1-here')); // 123
console.log(findId('https://some-domain.com/items/456/item-name-2-here')); // 456
String based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\/([a-z]+)\/.*/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items/abc/item-name-1-here')); // abc
console.log(findId('https://some-domain.com/items/cde/item-name-2-here')); // cde
ID in the name
Number based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\/[0-9a-z]+(?:-[0-9a-z]+)*-(\d+)/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items/item-name-1-here-123')); // 123
console.log(findId('https://some-domain.com/items/item-name-2-here-456')); // 456
Note:
In this case the
?:in the regular expression cancels the first group, that's why we still can get the id using index1of thematch.
String based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\/[0-9a-z]+(?:-[0-9a-z]+)*-([a-z]+)/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items/item-name-1-here-ABC')); // ABC
console.log(findId('https://some-domain.com/items/item-name-2-here-DEF')); // DEF
ID in request parameter
Number based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\?(\d+)/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items?123')); // 123
console.log(findId('https://some-domain.com/items?456')); // 456
String based IDs
// ONLINE-RUNNER:browser;
const expression = /^https?:\/\/some-domain\.com\/items\?([a-z]+)/i
const findId = (url) => {
const match = expression.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(findId('https://some-domain.com/items?abc')); // abc
console.log(findId('https://some-domain.com/items?def')); // def