Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting a string at nth occurrence of a character

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.

like image 393
Anonymous Avatar asked Mar 31 '11 02:03

Anonymous


People also ask

How do you find the nth occurrence of a character in a string?

1) Select Lookup from the drop-down list of Formula Type section; 2) Choose Find where the character appear Nth in a string in Choose a formula section; 3) Select the cell which contains the string you use, then type the specified character and nth occurrence in to the textboxes in the Arguments input section.

How do you cut a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split a string on second occurrence of character?

a. split("-", 2) will split the string upto the second occurrence of - . a.


1 Answers

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.

like image 141
alex Avatar answered Nov 03 '22 07:11

alex