0

Value is something like this: 12 23 345 3454 21.

I require to get numbers out of this and store into the Array so my array should look like values = new Array(12,23,345,3454,21);.

My problem is I can remove white spaces but it comes as 1223345345421.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ajax3.14
  • 1,647
  • 5
  • 24
  • 42

3 Answers3

7

You can use split(" ") to split the string along white spaces.

To be more thorough, you should trim the leading and trailing spaces, and split along multiple space characters:

> var numbers_in_string = "   12   23 345 3454    21    ";
> var numbers_in_array = numbers_in_string.trim().split(/\s+/);
> console.log(numbers_in_arrays)
["12", "23", "345", "3454", "21"]

EDIT

As @Sangdol has mentioned, trim() may not work in IE9, so you can use include one of these solutions to add trim() functionality to IE9. Or just replace trim() with replace(/^\s+|\s+$/g, ''). Either solutions will work as a work-around for cross-browser compatibility.

.replace(/^\s+|\s+$/g, '').split(/\s+/)
Community
  • 1
  • 1
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 2
    To save having to convert the elements to numbers later, you can add the following to the end of the solution: .map(function(val){return parseInt(val, 10);}) – Jules Jun 20 '12 at 14:00
2

If it's same pattern, you can use split():

var arr = '12 23 345 3454 21'.split(' ');
console.log(arr); // [12, 23, 345, 3454, 21]

Docs:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

As an alternative to split, you can use match:

' 12 23   345   3454   21 '.match(/\d+/g); //12,23,345,3454,21

Note that this is more specific to the pattern you are trying to extract, which may suit, or not. You only get the matched patterns so any intervening non-matches (including whitespace) are not returned.

RobG
  • 142,382
  • 31
  • 172
  • 209