TheWandererr TheWandererr - 10 days ago 7
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:

7:30


etc.

I filter the hours and minutes out with this JavaScript:
replace(/[^0-9]/g,'');
The result is 730.

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

Answer

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

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

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;
<p></p>
<p></p>
<p></p>

Comments