2

I want to split string

'something.somethingMore.evenMore[123].last'

to

['something',
'something.somethingMore',
'something.somethingMore.evenMore[123]',
'something.somethingMore.evenMore[123].last']

I can't figure out simple solution to split string by separator '.', but with preceding content of string.

ekad
  • 14,436
  • 26
  • 44
  • 46
Peter Dub
  • 491
  • 5
  • 12

5 Answers5

3

Modern JS programming style would be something like

str                                             //take the input
    .split('.')                                 //and split it into array of segments,
    .map(                                       //which we map into a new array,
        function(segment, index, segments)      //where for each segment
            return segments.slice(0, index+1)   //we take the segments up to its index
                .join(".")                      //and put them back together with '.'
            ;
         }
    )

This takes advantage of the fact that the Array#map function passes not only the current value, but also its index and the entire input array. That allows us to easily use slice to get an array containing all the segments up to the current one.

2

I wouldn't call my solution simple but:

function splitArrayIntoGoofyArray(val){
  var str =val.split("."), arr = [];
  for (var x = str.length; x >= 1; x--){
     var cnt = str.length - x;
     arr.push((cnt > 0) ? arr[cnt - 1] + "." + str[cnt] : str[cnt]);
  }
  return arr;
}
console.log(splitArrayIntoGoofyArray("aaa.bbb.ccc.ddd"));

http://jsfiddle.net/7tav4sue/

marteljn
  • 6,446
  • 3
  • 30
  • 43
2

You could try matching instead of splitting,

> var s = 'something.somethingMore.evenMore[123].last';
undefined
> var regex = /(?=(^((([^.]*)\.[^.]*)\.[^.]*)\.[^.]*))/g;
undefined
> regex.exec(s)
[ '',
  'something.somethingMore.evenMore[123].last',
  'something.somethingMore.evenMore[123]',
  'something.somethingMore',
  'something',
  index: 0,
  input: 'something.somethingMore.evenMore[123].last' ]

To get the desired output,

> regex.exec(s).slice(1,5)
[ 'something.somethingMore.evenMore[123].last',
  'something.somethingMore.evenMore[123]',
  'something.somethingMore',
  'something' ]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

It depends on what is simple solution. The easiest way to do it is to create first array with

var str = 'something.somethingMore.evenMore[123].last';
var arr = str.split('.');

And then fill new array with this data

var result = [];
for (var i = 0; i < arr.length; i++) {
    var item = [];
    for (var j = 0; j <= i; j++) {
        item.push(arr[j]);
    }
    result.push(item.join('.'))
}
Anton
  • 2,217
  • 3
  • 21
  • 34
1

I guess you'll need a loop :

while finding "." character, return in a list substring till new "." index. Use the last correct index found to start each search.

Hellin
  • 62
  • 8