2

In JavaScript, what is the best way to convert a well formatted string ("4,5,7,2") to an array ([4,5,7,2]):

var _intStr="3,5,7,8"var _intArr=[3,5,7,8]

1
  • Your question is "how do I tokenize a string?" Commented May 7, 2011 at 16:04

3 Answers 3

5
var _intArr = _intStr.split(",");

One thing worth mentioning is that such value _intStr = "5,,1" will produce array with three items, two are the expected "5" and "1" and one item which is empty string.

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

1 Comment

_instr.replace(/^,+|,+(,)|,+$/g, '$1').split(',') will remove any empty entries
1

Use the split function to split by a string or regex.

var arr = "1,2".split(",");

Now, if you actually want the elements of the resulting array to be numbers instead of strings, you can do something like this:

var arr = [];
"1,2,3,4,5".replace(/(?:'[^]*')|(?:[^, ]+)/g, function(match) {
    if (match) {
        arr[arr.length] = parseInt(match, 10);
    }
});

1 Comment

Not sure if the regex is perfect or not though.
1

Ok, thanks all for your helps.

I summarized your help in this way:

String.prototype.toArrInt = function(){

   _intStr =       this.replace(/^,+|,+(,)|,+$/g, '$1').split(',')
   for(var i=0,_intArr=[];i<_intStr.length;_intArr.push(parseInt(_intStr[i++])));
   return _intArr;

}

"3,5,6,,5".toArrInt();

Please correct me or improve my final code if is needed. Thanks,

Antonio

1 Comment

I would do it like this: String.prototype.toIntArray = function() { var arr = this.replace(/^,+|,+(,)|,+$/g, '$1').split(','); for (var i = 0; i < arr.length; ++i) { arr[i] = parseInt(arr[i], 10); } return arr; };

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.