Cutting a string at nth occurrence of a character

后端 未结 5 523
南方客
南方客 2020-11-27 04:01

What I want to do is take a string such as this.those.that and get a substring to or from the nth occurrence of a character. So, from the start of the string to

5条回答
  •  佛祖请我去吃肉
    2020-11-27 04:34

    I'm perplexed as to why you want to do things purely with string functions, but I guess you could do something like the following:

    //str       - the string
    //c         - the character or string to search for
    //n         - which occurrence
    //fromStart - if true, go from beginning to the occurrence; else go from the occurrence to the end of the string
    var cut = function (str, c, n, fromStart) {
        var strCopy = str.slice(); //make a copy of the string
        var index;
        while (n > 1) {
            index = strCopy.indexOf(c)
            strCopy = strCopy.substring(0, index)
            n--;
        }
    
        if (fromStart) {
            return str.substring(0, index);
        } else {
            return str.substring(index+1, str.length);
        }
    }
    

    However, I'd strongly advocate for something like alex's much simpler code.

提交回复
热议问题