function solve(s){ return s.replace(/R\.+L/g,str=>{ let len=str.length let halfLen=parseInt(len/2) let middle=len%2!==0?"#":"" return 'R'.repeat(halfLen)+middle+'L'.repeat(halfLen) }) .replace(/R\.+/g, str => 'R'.repeat(str.length)) .replace(/\.+L/g, str => 'L'.repeat(str.length)) .replace(/#/g, '.') } console.log(solve('RRRLLL.R')