2

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?

2

3 Answers 3

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"]
Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.