How to get the integer from a string in JavaScript

2 Answers

0 votes
function stringFirstInteger(str) {
    return str.match(/^\d+|\d+\b|\d+(?=\w)/g)[0];
}

console.log(stringFirstInteger('javascript2022 2023 2024')); 
console.log(stringFirstInteger('F 35 22 15')); 
console.log(stringFirstInteger('3 a 1 b 89 c')); 




/*
run:

"2022"
"35"
"3"

*/

 



answered Jun 5, 2022 by avibootz
0 votes
function stringFirstInteger(str) {
    return str.match(/^\d+|\d+\b|\d+(?=\w)/g).map(function (v) {return +v;})[0];
}

console.log(stringFirstInteger('javascript2022 2023 2024')); 
console.log(stringFirstInteger('F 35 22 15')); 
console.log(stringFirstInteger('3 a 1 b 89 c')); 




/*
run:

2022
35
3

*/

 



answered Jun 5, 2022 by avibootz
...