我想在时间字符串中围绕AM或PM包围一个范围。例如:
<span class="time">between 10:00AM and 14:00PM</span>
变为:
<span class="time">between 10:00<span class="suffix am">AM</span> and 14:00<span class="suffix pm">PM</span></span>
有关如何使用replace方法执行此操作的任何线索?
答案 0 :(得分:5)
我认为一个简单的replace()会这样做:
$('.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);
});
灵感来自:Fastest method to replace all instances of a character in a string
答案 1 :(得分:2)
您可以将am
/ pm
班级名称大写吗?在这种情况下,这将是一个解决方案:
$('.time').html(function(i, v) {
return v.replace(/(AM|PM)/g, '<span class="suffix $1">$1</span>');
});