简体   繁体   中英

how to strip out part of a string in a javascript array

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(ie " - 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]);
};

您可以在“”(空格)之后进行拆分 ,例如:

var desiredOption = optionStepTwo[i].split(" ")[0]

要在第一个空格处截断字符串:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM