Search code examples
javascriptregexregex-groupsubtotal

How to split string with subtotal prefix


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.


Solution

  • 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.