$('.hourfield').focusout(function() {
var h;
var m;
var timeStr = "";
var time = "";
var newFormat = "";
timeStr = $(this).val();
//Here I would like to remove all characters which isn't numbers
timeStr = timeStr.replace("/[^0-9\.]+/g","");
if(timeStr > 0) {
h = timeStr.substr(0,2);
m = timeStr.substr(2,2);
newFormat = h+':'+m;
//Add new values
$(this).val(newFormat);
}
});
2 Answers
$('.hourfield').focusout(function() {
var h;
var m;
var timeStr = "";
var CleanTimeStr = "";
var newFormat = "";
timeStr = $(this).val();
I did some minor changes to the replace() rule and just removed the "dots" which was the main purpose
CleanTimeStr = timeStr.replace(/[.]+/g,"");
if(CleanTimeStr > 0) {
h = CleanTimeStr.substr(0,2);
m = CleanTimeStr.substr(2,2);
newFormat = h+':'+m;
//Add new values
$(this).val(newFormat);
}
});
So now it works fine, thanks!
"/[^0-9\.]+/g". You wanted it to be a regex, but you ended up with a string. Lose the quotes and you'll be fine.