TheWandererr TheWandererr - 3 months ago 35
Javascript Question

Add colon to string at a certain position

I have a website where I am calculating the hours and minutes between two times (Starttime Endtime) which has been entered inside two input elements. The result is saved inside a label.

Here is an example:

Starttime: 08:00
Endtime: 15:30
TimeSpend: 7 hours 30 Minutes

I need to send the value Timespend back to my backend but not in this form. I want to send it in a form like:



I filter the hours and minutes out with this JavaScript:
The result is 730.

How can I add a colon between 7 and 30 to let look
730 --> 7:30
? The Same should work for
1120 --> 11:20


You can apply a second regular expression to timespend, which identifies the last two characters and inserts a colon in front:


Working example:

var paragraphs = document.getElementsByTagName('p');

var timespend = '7 hours 30 Minutes';

paragraphs[0].textContent = timespend;

timespend = timespend.replace(/[^0-9]/g,'');

paragraphs[1].textContent = timespend;

timespend = timespend.replace(/(.{2})$/,':$1');

paragraphs[2].textContent = timespend;