I am getting an array like below after doing the matches. [ '10 am', '5 pm', 'by appointment only' ] I would like to append text to only for time and return in this format.
"10 am to 5 pm by appointment only"
But when I join like below
[ '10 am', '5 pm', 'by appointment only' ].join( 'to' );
I am getting result as
"10 am to 5 pm to by appointment only"
So with the help of regular expression is there a way to to remove 'to' only from 3rd element of array so that when joining it won't append 'to ' again.
CodePudding user response:
const [start,end,describe] = [ '10 am', '5 pm', 'by appointment only' ];
const finalText = `${start} to ${end} ${describe}`;
console.log(finalText)
CodePudding user response:
You can use Array.prototype.reduce():
const arr = ['10 am', '5 pm', 'by appointment only']
const result = arr.reduce((a, c, i) => (a = c (i ? ' ' : ' to '), a), '')
console.log(result)