I have a dynamically formed string like - part1.abc.part2.abc.part3.abc
whose length is unknown
我有一个动态形成的字符串,如 - part1.abc.part2.abc.part3.abc,其长度未知
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
.
在这个字符串中,我想根据第二次出现的“。”获取子字符串。所以我可以得到和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
如果字符串是 - part1.abc.part2.abc.part3.abc.part4输出必须像part1.abc part2.abc part3.abc part4
How to get this?
怎么弄这个?
3 个解决方案
#1
3
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"]
#2
2
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);
#3
1
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"]
#1
3
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"]
#2
2
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);
#3
1
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"]