I have a dynamically formed string like - part1.abc.part2.abc.part3.abc
whose length is unknown
In this string I want to get the substring based on second occurrence of "." so that I can get and part1.abc
part2.abc
part3.abc
.
And if the string is like - part1.abc.part2.abc.part3.abc.part4
output must be like part1.abc
part2.abc
part3.abc
part4
How to get this?
Something like this :
str="part1.abc.part2.abc.part3.abc.part4"
temp=str.split('.');
out=[]
for(i=0; i<temp.length;i=i+2)
out.push(temp.slice(i,i+2).join('.'));
//["part1.abc", "part2.abc", "part3.abc", "part4"]
As suggested in my comment, the simplest (and fastest) way is to use a regular expression and match:
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);
Simple function which allows you to specify the number of items to join together and delimiter which you can use to join them.
var concatBy = function(list, delimiter, by) {
var result = [];
for (var i = 0; i < list.length; i += by) {
result.push(list.slice(i, i + by).join(delimiter))
}
return result;
}
concatBy('part1.abc.part2.abc.part3.abc'.split('.'), '.', 2) // returns concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2)
concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2) // returns ["part1.abc", "part2.abc", "part3.abc", "part4"]