How to wrap a span around “PM” and “AM” in a string?
I want to wrap the gap around AM or PM in a time line. For instance:
<span class="time">between 10:00AM and 14:00PM</span>
becomes:
<span class="time">between 10:00<span class="suffix am">AM</span> and 14:00<span class="suffix pm">PM</span></span>
Any clue on how to get the replace method for this?
I think simple replace () will do this:
$('.time').each(function() {
var newMarkup = $(this).html().replace(/AM/g, '<span class="suffix am">AM</span>')
.replace(/PM/g, '<span class="suffix pm">PM</span>');
$(this).html(newMarkup);
});
Inspired: The fastest way to replace all instances of a character in a string
Could you use class names am/ pm? In this case, this will be the solution:
$('.time').html(function(i, v) {
return v.replace(/(AM|PM)/g, '<span class="suffix $1">$1</span>');
});
Live demo: http://jsfiddle.net/pVWh6/