Monday, December 11, 2023
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  134] [ 4]  / answers: 1 / hits: 69037  / 13 Years ago, thu, march 31, 2011, 12:00:00

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.


More From » string

 Answers
301

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.


[#93001] Tuesday, March 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
davisbrandtm

Total Points: 387
Total Questions: 99
Total Answers: 106

Location: Tuvalu
Member since Sat, Feb 11, 2023
11 Months ago
;