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.
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\/(\d+)\/.*/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items/123/item-name-1-here')); // 123
15
console.log(findId('https://some-domain.com/items/456/item-name-2-here')); // 456
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\/([a-z]+)\/.*/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items/abc/item-name-1-here')); // abc
15
console.log(findId('https://some-domain.com/items/cde/item-name-2-here')); // cde
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\/[0-9a-z]+(?:-[0-9a-z]+)*-(\d+)/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items/item-name-1-here-123')); // 123
15
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 index1
of thematch
.
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\/[0-9a-z]+(?:-[0-9a-z]+)*-([a-z]+)/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items/item-name-1-here-ABC')); // ABC
15
console.log(findId('https://some-domain.com/items/item-name-2-here-DEF')); // DEF
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\?(\d+)/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items?123')); // 123
15
console.log(findId('https://some-domain.com/items?456')); // 456
xxxxxxxxxx
1
const expression = /^https?:\/\/some-domain\.com\/items\?([a-z]+)/i
2
3
const findId = (url) => {
4
const match = expression.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findId('https://some-domain.com/items?abc')); // abc
15
console.log(findId('https://some-domain.com/items?def')); // def