With this line of code
$("body").html($("body").html().replace(/1800/g,'6:00pm'));
I can replace the word, but how can I make it more dynamic with this script?
var getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2));
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
My HTML code is e.g
Your class will start at 1900, please be there by 1845.
Which will be counted to
Your class will start at 07:00pm, please be there by 06:45pm.
I tried this:
$("body").html($("body").html().replace(fourDigitTime, getFormattedTime(fourDigitTime)));
var fourDigitTime = document.getElementById('fourDigitTime').value;
var getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2));
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
It does not work..
[edited after EmersonF cleared up that all four letter times should be replaced]
You can use a function as the second argument to replace:
The part of the string that is “captured” using the parenthesis in the
regular expression is handed to the function as the second argument (here called p1)
See http://jsfiddle.net/bjelline/pb8d2/ for a working example
Note: the regular expression cannot tell the year 2015 apart from quater
past 8pm, and will convert the year to a time!