46795

Question:
how to extract numbers from string using Javascript? Test cases below:
string s = 1AA11111
string s1= 2111CA2
string s result = 111111
string s1 result = 211112
My code below is not working:
var j = 0;
var startPlateNums = "";
while (j <= iStartLength && !isNaN(iStartNumber.substring(j, j + 1))){
startPlateNums = startPlateNums + iStartNumber.substring(j, j + 1);
j++;
}
Answer1:How about a simple regexp
s.replace(/[^\d]/g, '')
or as stated in the comments
s.replace(/\D/g, '')
<a href="http://jsfiddle.net/2mguE/" rel="nofollow">http://jsfiddle.net/2mguE/</a>
Answer2:You could do: <strong>EDITED:</strong>
var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]
Answer3:A regex replace would probably the easiest and best way to do it:
'2111CA2'.replace(/\D/g, '');
However here's another alternative without using regular expressions:
var s = [].filter.call('2111CA2', function (char) {
return !isNaN(+char);
}).join('');
Or with a simple for loop:
var input = '2111CA2',
i = 0,
len = input.length,
nums = [],
num;
for (; i < len; i++) {
num = +input[i];
!isNaN(num) && nums.push(num);
}
console.log(nums.join(''));