leora
leora

Reputation: 196489

in javascript / jquery how can i parse a string (with inconsistence spaces) into an array

i have a string that looks like this:

1, 2, 4, 4,5, 6  

NOTE: notice the inconsistency in spaces

what is the best way to convert this to an array of integers

Upvotes: 0

Views: 418

Answers (7)

kennebec
kennebec

Reputation: 104770

var str= '1, 2, 4, 4,5, 6  ';
var integerarray= str.match(/\d+/g).map(Number);

Upvotes: 0

RobG
RobG

Reputation: 147383

Hey, just to round out the offerings... the quickest way to convert a numeric string to number is the unary operator +. e.g.

var nums = ' 1, 2, 4, 4,5, 6 '.replace(/^\s+|\s+$/g,'').split(/\D+/);
var i = nums.length;
while (i--) {
  nums[i] = +nums[i]; 
}

You could also use:

nums[i] = nums[i] | 0; 

You may be better off to convert them to numbers when you use them.

Upvotes: 0

meouw
meouw

Reputation: 42140

As Regular Expressions seem to be quite popular in the answers submitted so far I thought I'd add a couple of RexExp based solutions

If you really need integers:

var str = '1, 2, 4,    4,5, 6  ';
var arr = [];

str.replace( /\d+/g, function( i ) {
    arr.push( parseInt( i, 10 ) );
});

console.log( arr ); //[1, 2, 4, 4, 5, 6]

If strings will do

var str = '1, 2, 4,    4,5, 6  ';

var arr = str.match( /\d+/g );

console.log( arr ) //["1", "2", "4", "4", "5", "6"]

Upvotes: 1

Jeaf Gilbert
Jeaf Gilbert

Reputation: 11981

var array = [];
var string = "1, 2, 4, 4,5, 6  ";
$(string.replace(/\s+/g, "").split(",")).each(function() {
    array.push(parseInt(this));
});

return array;

Upvotes: 0

jensgram
jensgram

Reputation: 31508

var s = '1, 2, 4,    4,5, 6  ';
var o = s.trim().split(/ *, */);

(Demo.) Trimming first (may not be necessary), then splitting on comma (,), discarding all spaces ().


UPDATE
Casting to integer using jQuery to iterate (demo):

var s = '1, 2, 4,    4,5, 6  ';
var a = s.trim().split(/ *, */);
var o = $.map(a, function(elm) {
    return parseInt(elm, 10);
});

Note: A simple for loop could have been used instead (demo):

var s = '1, 2, 4,    4,5, 6  ';
var a = s.trim().split(/ *, */);
var o = [];
for (i = 0, j = a.length; i < j; i++) {
    o.push(parseInt(a[i], 10));
};

Upvotes: 4

ysrb
ysrb

Reputation: 6740

Try this:

   var inputStr = "1, 2, 4, 4,5, 6 ";
    var arrInput = inputStr.split(",");
    var arrOutput = new Array();
    for(var ctr in arrInput){
       arrOutput[ctr] = parseInt(arrInput[ctr].replace(" ",""));
    }

Upvotes: 0

Emmerman
Emmerman

Reputation: 2343

var arr = str.split(/,\s*/);

Upvotes: 0

Related Questions