1

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++;
} 
2
  • 1
    what is iStartLength initialized to ? Also, what is iStartNumber ? Commented Nov 14, 2013 at 22:36
  • Your while loop will break as soon as a non-number is encountered (isNaN becomes true). Looking at your sample input and output, that's not what you want. You probably want to move that condition into an if block inside your loop. Commented Nov 14, 2013 at 22:38

3 Answers 3

4

How about a simple regexp

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

or as stated in the comments

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

http://jsfiddle.net/2mguE/

Sign up to request clarification or add additional context in comments.

2 Comments

I was going to post /\D/g. Saves 1 character!
@ScottMermelstein Saves more than 1, it saves 3 ;)
2

You could do: EDITED:

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

3 Comments

That will fail for numbers that comes after non-numeric characters.
It would require a global flag: "123asas2342a".match(/\d+/g) # => ["123", "2342"], but +1 for matching and not just replacing everything that's not a number with an empty string ''
You may want ('...'.match(/\d+/g) || []).join('') just in case there are no digits
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.