Cutting a string at nth occurrence of a character

JavascriptStringSubstringSlice

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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;

Solution 5 - Javascript

If you really want to stick to string methods, then:

// Return a substring of s upto but not including
// the nth occurence of c
function getNth(s, c, n) {
  var idx;
  var i = 0;
  var newS = '';
  do {
    idx = s.indexOf(c);
    newS += s.substring(0, idx);
    s = s.substring(idx+1);
  } while (++i < n && (newS += c))
  return newS;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnonymousView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - Javascriptuser2165842View Answer on Stackoverflow
Solution 3 - JavascriptNT3RPView Answer on Stackoverflow
Solution 4 - JavascripthookeView Answer on Stackoverflow
Solution 5 - JavascriptRobGView Answer on Stackoverflow