Reputation: 369
I have a special time format from json, ex: 07_23 means 07:00 - 23:00,and when it shows 24, ex: 07_24 it should change to 07:00 - 23:59.
My code is here:
$(document).ready(function () {
var json = [{"name":"Meee","time":"07_24"}];
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + json[i].time + ":00" + "</td>");
$('table').append(tr);
$("td:contains('_')").text($("td:contains('_')").text().replace('_', ':00-'));
$("td:contains('24')").text($("td:contains('24')").text().replace('24:00', '23:59'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<th>Name</th>
<th>Time</th>
</tr>
</table>
I think my code is a little bit stupid, are there any best way to remove 07_24 underline, add :00 for each number, and change 24 to 23:59? Or can I use regular expression to achieve that goal?
Upvotes: 0
Views: 99
Reputation: 24001
as @Spencer Wieczorek mentioned in comment .. your code is good .. but If you need to simplify it a little bit .. or just need to know another way to doing that
$(document).ready(function () {
var json = [{"name":"Meee","time":"07_24"}];
for (var i = 0; i < json.length; i++) {
var Splittime = json[i].time.split('_');
var all_time = Splittime[0]+':00-'+((Splittime[1] == 24)? '23:59' : Splittime[1]+':00');
tr = $('<tr/>');
tr.append("<td>" + json[i].name + "</td><td>" + all_time + "</td>");
$('table').append(tr);
}
});
Working Demo another Demo
Upvotes: 1
Reputation: 474
You change always the same part so use regular expression is not necessary. Because you just have to change the _ to :00- and the 24:00 to 23:59 it's constant so you dont need regular expression.
Upvotes: 0
Reputation: 13409
You can write a pretty simple regular expression to do this:
var new_string = "some string 07_23 bla bla".replace(/([0-2][0-9])_24/g,"$1:00-23:59").replace(/([0-2][0-9])_([0-2][0-9])/g,"$1:00-$2:00");
which outputs "bla bla some string 07:00-23:00 bla bla"
Upvotes: 0
Reputation: 1078
http://jsfiddle.net/xfdqj6oo/2/
var formatTime = function(time) {
return time.split('_').map(function(hour) {
return hour === '24'? '23:59': hour + ':00';
}).join('-');
}
$(document).ready(function () {
var json = [{"name":"Meee","time":"07_24"}];
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + formatTime(json[i].time) + "</td>");
$('table').append(tr);
}
});
Basically there is a function to take care of the time formatting/transformation.
Upvotes: 0