user169867
user169867

Reputation: 5870

How to get an int[] from a string of integers in javascript / jQuery?

I'd like to allow a user to be able to enter a list of IDs into a textarea and allow the IDs to be seperated by whitespace such as a new line as well as by commas.

Then I'd like to convert that into an int[] or throw an error if the string is bad: contains letters, decimals, etc.

But I'm having trouble working it out.

Can anyone give an example of how to do this?

I'd apprecuate any help.

Upvotes: 1

Views: 147

Answers (2)

icktoofay
icktoofay

Reputation: 129001

If you use the split method, you can pass it a regular expression to split by. For example:

var myArray=myString.split(/[^\d]+/);

This would return an array of strings, each containing a string representation of an integer. Furthermore, you can then use the parseInt function to parse those string representations to integers, like so:

var myIntArray=[];
for(var i=0;i<myStringArray.length;i++) {
    myIntArray.push(parseInt(myStringArray[i], 10));
}

You can see a full example with some jQuery helpers (specifically, jQuery.map) here.

Upvotes: 4

Mark Elliot
Mark Elliot

Reputation: 77044

Take a look at the split function.

What you'll need to do is split the text in the textarea based on your desired delimiter, then iterate through the array to convert to integers. Since the split function takes a single separator, you'll need to normalize the input a bit, say by converting line breaks to whitespace.

Upvotes: 1

Related Questions