EN
JavaScript - get number after word using regex
0 points
In this article, we would like to show you how to
Quick solution:
xxxxxxxxxx
1
const text = 'some-word123';
2
const expression = /some-word(\d+)/i; // new RegExp('some-word(\\d+)', 'i');
3
4
const match = expression.exec(text);
5
6
if (match) {
7
console.log(match[1]); // '123'
8
}
In this example, we construct a regular expression that matches some-word
with a number after the word. To get only the number group (\d+
) we need to use brackets notation (match[1]
).
xxxxxxxxxx
1
const expression = /some-word(\d+)/i; // new RegExp('some-word(\\d+)', 'i');
2
3
const findNumber = (text) => {
4
const match = expression.exec(text);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(findNumber('some-word123')); // 123
15
console.log(findNumber('some text... some-word456')); // 456