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.

Leave a Comment