views:

207

answers:

3
"abc def"
"abcd efgh"

If I have a large string with a space that separates two substrings of varying length, what's the best way to extract each of the substrings from the larger string?

Because this is a string rather than an array, array syntax s[0] will only retrieve the first letter of the string ('a'), rather than the first substring.

+14  A: 

Use the split method of the String object:

"abc def".split(' ')[0] // Returns "abc"

Works like this:

"string".split('separator') // Returns array
musicfreak
just had to post a second before me, didn't you?
Mark
Yep. :)
musicfreak
+9  A: 
var arr = "abc def".split(" ");
document.write(arr[0]);

should work

Mark
A: 

Both above Answer's are right I am just putting it so that user can do some operation with every token. All you need to add a loop for that.

function splitStr(str){
    var arr = str.split(" ");
    for(i=0 ;i < arr.length ; i++){
        //You will get a token here 
        // var token = arr[i];
        // Do some thing with this token
    }
}

One can return the array for any other operation in other function as

function splitStr(str){
    var arr = str.split(" ");
    return arr;
}
Umesh Aawte
I'm sorry but what exactly is the point of the second function, `splitStr`? Isn't it a bit redundant?
musicfreak
Yes, it is only a sample code or you can say example of the string split feature which returns a array of tokens.
Umesh Aawte