Cutting a string at nth occurrence of a character

Anonymous picture Anonymous · Mar 31, 2011 · Viewed 53k times · Source

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 the 2nd occurrence of . would return this.those. Likewise, from the 2nd occurrence of . to the end of the string would return that. Sorry if my question is foggy, it's not that easy to explain. Also, please do not suggest making extra variables, and the result will be in a string and not an array.

Answer

alex picture alex · Mar 31, 2011

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.