in javascript / jquery how can i parse a string (with inconsistence spaces) into an array
i have a开发者_StackOverflow 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
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));
};
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"]
var arr = str.split(/,\s*/);
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(" ",""));
}
var array = [];
var string = "1, 2, 4, 4,5, 6 ";
$(string.replace(/\s+/g, "").split(",")).each(function() {
array.push(parseInt(this));
});
return array;
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.
var str= '1, 2, 4, 4,5, 6 ';
var integerarray= str.match(/\d+/g).map(Number);
精彩评论