3

I want to wrap a span around the AM or PM in a time string. For example:

<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 to do this?

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148

2 Answers2

5

I think a simple replace() would do it:

$('.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 by: Fastest method to replace all instances of a character in a string

Community
  • 1
  • 1
Kon
  • 27,113
  • 11
  • 60
  • 86
  • Alternatively, you can add the spans with 'suffix' class beforehand, and then test for AM/PM existence in the markup and call jQuery's addClass('am') or addClass('pm') on the span. – Kon May 05 '11 at 15:09
  • 4
    @Marcel, I'm pretty that IS a regex. :) – Kon May 05 '11 at 15:10
  • Uhm, yes, you're right. :) But `.replace('AM', 'AM', 'g')` doesn't use a regex, which is rather costly (but perhaps the JavaScript engine does internally use one). – Marcel Korpel May 05 '11 at 15:16
  • it IS a regex! at least the /AM/g part. if you wanted to make it case insensitive you could add an i. for example /AM/gi would make it match AM or am. – ryanmarc May 05 '11 at 15:17
  • Regarding the costly comment, I wouldn't totally disagree - that's why I provided an alternative idea that only applies CSS classes, instead of manipulating the DOM. – Kon May 05 '11 at 15:20
  • Can manipulate the DOM though any other means that JS, no access to HTML, so this answer is the right one as is. – Mild Fuzz May 05 '11 at 21:43
2

Could you capitalize the am/pm class names? In that case this would be a solution:

$('.time').html(function(i, v) {
    return v.replace(/(AM|PM)/g, '<span class="suffix $1">$1</span>');
});

Live demo: http://jsfiddle.net/pVWh6/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385