Split a string only the at the first n occurrences of a delimiter

后端 未结 18 906
有刺的猬
有刺的猬 2020-12-24 06:22

I\'d like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn\'t there a more straight forward appr

18条回答
  •  天命终不由人
    2020-12-24 06:43

    For this you could use Split(delimiter) and choose a delimiter.

    var testSplit = "Split this, but not this";
    var testParts= testSplit.Split(",");
    
    var firstPart = testParts[1];
    
    // firstPart = "Split this"
    

    Not 100% on my syntax I havent used javascript in quite some time. But I know this is how its done...

    EDIT** Sorry, my mistake. Now I believe I know what your asking and I think the easiest way to do this is using substr. Very easy, no loops required. Just made an example, works perfect

    // so first, we want to get everything from 0 - the first occurence of the comma.
    // next, we want to get everything after the first occurence of the comma.  (if you only define one parameter, substr will take everything after that parameter.
    
    var testString = "Split this, but this part, and this part are one string";
    var part1 = testString.substr(0,testString.indexOf(',')); 
    var part2 = testString.substr(testString.indexOf(','));
    
    //part1 = "Split this"
    //part2= "but this part, and this part are one string"
    

提交回复
热议问题