Skip to content Skip to sidebar Skip to footer

How To Extract Numbers From String Using Javascript?

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

Solution 1:

How about a simple regexp

s.replace(/[^\d]/g, '')

or as stated in the comments

s.replace(/\D/g, '')

http://jsfiddle.net/2mguE/


Solution 2:

You could do: EDITED:

var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]

Solution 3:

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(''));

Post a Comment for "How To Extract Numbers From String Using Javascript?"