Split string on the first white space occurrence

后端 未结 13 2002
孤街浪徒
孤街浪徒 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:40

    I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.

    As an example, let's get the first and "rest" components of a name:

    const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
    console.log({ first, rest });
    
    // As array
    const components = 'Surma'.split(/\s+(.*)/);
    console.log(components);

    0 讨论(0)
  • 2020-11-28 20:41
    var arr = [];             //new storage
    str = str.split(' ');     //split by spaces
    arr.push(str.shift());    //add the number
    arr.push(str.join(' '));  //and the rest of the string
    
    //arr is now:
    ["72","tocirah sneab"];
    

    but i still think there is a faster way though.

    0 讨论(0)
  • 2020-11-28 20:42

    Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.

    This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.

    var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
    var galleryID = galleryClass.split(" ").shift(); // = gallery_148
    galleryID = galleryID.split("_").pop(); // = 148
    //or
    galleryID = galleryID.substring(8); // = 148 also, but less versatile 
    

    I'm sure it could be compacted into less lines but I left it expanded for readability.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-28 20:45

    Javascript doesn't support lookbehinds, so split is not possible. match works:

    str.match(/^(\S+)\s(.*)/).slice(1)
    

    Another trick:

    str.replace(/\s+/, '\x01').split('\x01')
    

    how about:

    [str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]
    

    and why not

    reverse = function (s) { return s.split('').reverse().join('') }
    reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)
    

    or maybe

    re = /^\S+\s|.*/g;
    [].concat.call(re.exec(str), re.exec(str))
    

    2019 update: as of ES2018, lookbehinds are supported:

    str = "72 tocirah sneab"
    s = str.split(/(?<=^\S+)\s/)
    console.log(s)

    0 讨论(0)
  • 2020-11-28 20:45

    You can also use .replace to only replace the first occurrence,

    ​str = str.replace(' ','<br />');
    

    Leaving out the /g.

    DEMO

    0 讨论(0)
提交回复
热议问题