Extract number from string in typescript
To extract a number from a string in typescript, use the match()
method with the /\d+/g
regex it will find all numbers from the string and return as an array of numbers.
const REGEX = /\d+/g;
let sampleString: string = "#div-name-1234-characteristic:561613213213";
let arrOfNumber: Array<number> = sampleString.match(REGEX);
// 👇️ [ '1234', '561613213213' ]
console.log(arrOfNumber)
Today, I’m going to show you How to i extract a number from a string in typescript, as mentioned above, I’m going to use the use match()
and join()
method with /\d+/g
regex to extract numbers from string and convert in digits.
Let’s start today’s tutorial how do you extract numbers from the string in typescript?
In this example, we will do
- extract number from string
- got extracted array of numbers and convert it a single string
- convert string to digits
utils.ts
const REGEX = /\d+/g;
let sampleString: string = "#div-name-1234-characteristic:561613213213";
let arrOfNumber: Array<number> = sampleString.match(REGEX);
// 👇️ [ '1234', '561613213213' ]
console.log(arrOfNumber)
let numStr: string = arrOfNumber.join('');
// 👇️ '1234561613213213'
console.log(numStr)
let num: number = +numStr;
// 👇️ 1234561613213213
console.log(num)
In the above code example, we will do all steps separately but if you want to sort the version of the code look following code.
const REGEX = /\d+/g;
let sampleString: string = "#div-name-1234-characteristic:561613213213";
let num: number = +sampleString.match(REGEX).join('');
// 👇️ 1234561613213213
console.log(num)
I hope it helps you, All the best 👍.