Cutting a string at nth occurrence of a character

You could do it without arrays, but it would take more code and be less readable.

Generally, you only want to use as much code to get the job done, and this also increases readability. If you find this task is becoming a performance issue (benchmark it), then you can decide to start refactoring for performance.

var str = 'this.those.that',
    delimiter = '.',
    start = 1,
    tokens = str.split(delimiter).slice(start),
    result = tokens.join(delimiter); // those.that
    
console.log(result)

// To get the substring BEFORE the nth occurence
var tokens2 = str.split(delimiter).slice(0, start),
    result2 = tokens2.join(delimiter); // this

console.log(result2)

jsFiddle.


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.


Try this :

"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){3}/, '');
"xcv.xcv.x"

"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){**nth**}/, ''); - where is nth is the amount of occurrence to remove.