0

I have several arrays that are built similar to this:

exampleArray=new array(
"A01 - Blah Blah Blah",
"A01A - Blah Blah Blah Blah")

I'm using these Arrays to populate options in a form and I need to strip out everything after the first space(i.e. " - Blah Blah Blah") for the values of a given option. The options and values are currently being generated with this code:

for(i=0; i<optionStepTwo.length; i++) {
    elementStepTwo.options[elementStepTwo.options.length] = 
            new Option(optionStepTwo[i], optionStepTwo[i]);
};
4
  • so A01 would be the option value, and Blah blah blah woul dbe the displayed text? If they're going into an arra, why not store the two parts in separate elements? This'd save you having to use string operations to yank them apart again later. Commented Jul 14, 2012 at 17:21
  • Actually that would help, I'm just not sure how to write the array that way. Commented Jul 14, 2012 at 17:24
  • var x = [['A01', 'blahblahblah'], ['a01a', 'blahblah']]; which'd make x[1][0] be a01a. Commented Jul 14, 2012 at 17:24
  • Awesome, I'll have to play around with that. Commented Jul 14, 2012 at 17:40

3 Answers 3

1

You could do a split after " "(space), like:

var desiredOption = optionStepTwo[i].split(" ")[0]
Sign up to request clarification or add additional context in comments.

Comments

1

To truncate a string at the first space:

var myStringBeforeFirstSpace = myString.split(" ")[0];

Comments

1

If you are trying to split only at the first space.

var string = 'A01A - Blah Blah Blah Blah';
var firstSpace = string.indexOf(' ');
alert(string.substr(0, firstSpace));​​​​​​​​​​​​​​​​​​​​​​​​​

Working Example

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.