1

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.

1
  • 1
    Literally as you described. Read textarea value, split by separators, convert to int's, throw error if 'string is bad'. In what part were you 'having trouble'? Commented Jun 21, 2010 at 4:23

2 Answers 2

4

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.

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

1 Comment

I didn't know of \D, and [^\d] worked just fine, so that's why I used it.
1

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.

Comments

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.