Split string on the first white space occurrence

后端 未结 13 2080
孤街浪徒
孤街浪徒 2020-11-28 20:07

I didn\'t get an optimized regex that split me a String basing into the first white space occurrence:

var str=\"72 tocirah sneab\";

I need

13条回答
  •  感动是毒
    2020-11-28 20:43

    The following function will always split the sentence into 2 elements. The first element will contain only the first word and the second element will contain all the other words (or it will be a empty string).

    var arr1 = split_on_first_word("72 tocirah sneab");       // Result: ["72", "tocirah sneab"]
    var arr2 = split_on_first_word("  72  tocirah sneab  ");  // Result: ["72", "tocirah sneab"]
    var arr3 = split_on_first_word("72");                     // Result: ["72", ""]
    var arr4 = split_on_first_word("");                       // Result: ["", ""]
    
    function split_on_first_word(str)
    {
        str = str.trim();  // Clean string by removing beginning and ending spaces.
    
        var arr = [];
        var pos = str.indexOf(' ');  // Find position of first space
    
        if ( pos === -1 ) {
            // No space found
            arr.push(str);                // First word (or empty)
            arr.push('');                 // Empty (no next words)
        } else {
            // Split on first space
            arr.push(str.substr(0,pos));         // First word
            arr.push(str.substr(pos+1).trim());  // Next words
        }
    
        return arr;
    }
    

提交回复
热议问题