Cutting a string at nth occurrence of a character

后端 未结 5 515
南方客
南方客 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:31

    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.

提交回复
热议问题