Split string once in javascript?

前端 未结 13 915
南笙
南笙 2020-11-29 03:23

How can I split a string only once, i.e. make 1|Ceci n\'est pas une pipe: | Oui parse to: [\"1\", \"Ceci n\'est pas une pipe: | Oui\"]?

The

相关标签:
13条回答
  • 2020-11-29 03:35

    This isn't a pretty approach, but works with decent efficiency:

    var string = "1|Ceci n'est pas une pipe: | Oui";
    var components = string.split('|');
    alert([components.shift(), components.join('|')]​);​​​​​
    

    Here's a quick demo of it

    0 讨论(0)
  • 2020-11-29 03:35

    Try this:

    function splitOnce(input, splitBy) {
        var fullSplit = input.split(splitBy);
        var retVal = [];
        retVal.push( fullSplit.shift() );
        retVal.push( fullSplit.join( splitBy ) );
        return retVal;
    }
    
    var whatever = splitOnce("1|Ceci n'est pas une pipe: | Oui", '|');
    
    0 讨论(0)
  • 2020-11-29 03:36

    An alternate, short approach, besides the goods ones elsewhere, is to use replace()'s limit to your advantage.

    var str = "1|Ceci n'est pas une pipe: | Oui";
    str.replace("|", "aUniquePhraseToSaySplitMe").split("aUniquePhraseToSaySplitMe");
    

    As @sreservoir points out in the comments, the unique phrase must be truly unique--it cannot be in the source you're running this split over, or you'll get the string split into more pieces than you want. An unprintable character, as he says, may do if you're running this against user input (i.e., typed in a browser).

    0 讨论(0)
  • 2020-11-29 03:38

    if you wanna use a "pipeline", reduce is your friend

    const separator = '|'
    jsonNode.split(separator)
       .reduce((previous, current, index) =>
        {
            if (index < 2) previous.push(current)
            else previous[1] += `${separator}${current}`
            return previous
        }, [])
        .map((item: string) => (item.trim()))
        .filter((item: string) => (item != ''))
    
    0 讨论(0)
  • 2020-11-29 03:46

    You can use:

    var splits = str.match(/([^|]*)\|(.*)/);
    splits.shift();
    

    The regex splits the string into two matching groups (parenthesized), the text preceding the first | and the text after. Then, we shift the result to get rid of the whole string match (splits[0]).

    0 讨论(0)
  • 2020-11-29 03:46

    More effective method:

    const str = "1|Ceci n'est pas une pipe: | Oui"
    
    const [head] = str.split('|', 1);
    
    const result = [head, str.substr(head.length + 1)]
    
    console.log(result);

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