Использование регулярного выражения в этом случае может быть не лучшим выбором. Вы можете просто разделить вашу строку на .
и затем присоединиться к ним, когда вам это нужно.
function recursivelySplitText(arrayOfString, output) {
// check if the output is set, otherwise create it.
if(!output) {
output = [];
}
// we add the current value to the output
output.push(arrayOfString.join('.'));
// we remove the first element of the array
arrayOfString.splice(0, 1);
// if we just have one element left in the array ( com ) we return the array
// otherwise, we call the function again with the newly splitted array.
return arrayOfString.length === 1 ? output : recursivelySplitText(arrayOfString, output);
}
const text = 'in.k1.k2.k3.k4.com';
// we need to split it first to have an array of string rather than a string.
console.log(recursivelySplitText(text.split('.')));
Здесь я использовал рекурсию, потому что это весело, но это не единственный способ получить тот же результат.