Cutting a string at nth occurrence of a character

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

    Just in case somebody needs both "this" and "those.that" in a way as alex described in his comment, here is a modified code:

    var str = 'this.those.that',
        delimiter = '.',
        start = 1,
        tokens = str.split(delimiter),
          result = [tokens.slice(0, start), tokens.slice(start)].map(function(item) {
        return item.join(delimiter);
      }); // [ 'this', 'those.that' ] 
    
    document.body.innerHTML = result;

提交回复
热议问题