0

I have a string of dates in which I wish to truncate at the first comma. e.g., I would like:

  • Today, July 9, 2014
  • Tomorrow, July 10, 2014
  • July 11, 2014

To Display:

  • Today
  • Tomorrow
  • July 11

Using:

var longDay = $('.daily_forecast').text(); 
var shortDay = jQuery.trim(longDay).substring(0, 12).split(',').slice(0, -1);
$('.daily_forecast').replaceWith('<span>' + shortDay + '</span>');

will properly truncate the content, however, all results are returning "Today".

I believe I need to loop through the elements using .each but am having difficulty doing so.

Thank you.

2 Answers2

2

Pass a function to .html(). It will be called on each element that matches the selector, and receive the old contents as a parameter. It can then return the replacement.

$('.daily_forecast').html(function(index, longDay) {
    var shortDay = jQuery.trim(longDay).substring(0, 12).split(',').slice(0, -1);
    return '<span>' + shortDay + '</span>';
});

DEMO

If the original elements contain HTML rather than plain text, and you need to remove all the markup before replacing it, you'll need to use .each explicitly:

$('.daily_forecast').each(function() {
    var longDay = $(this).text();
    var shortDay = jQuery.trim(longDay).substring(0, 12).split(',').slice(0, -1);
    $(this).html('<span>' + shortDay + '</span>');
});

You probably don't want to use .replaceWith, as this removes the entire .daily_forecast element. Use .html() to replace its contents.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • No, it operates on each matching element independently. There's an implicit `.each()` being done automatically by jQuery. – Barmar Jul 09 '14 at 16:52
  • A slight difference here is that the original code was reading `text` and not `html`. It is impossible to say if this is an important distinction as the question did not include the relevant html. Similarly, the `replaceWith` would replace the element whereas this would insert a span into the element. – James Montagne Jul 09 '14 at 16:57
0

using regEx

$('.daily_forecast').html(function(index, longDay) {
    var shortDay = jQuery.trim(longDay).match(/[\w\s]+(?=,)/)[0]
    return '<span>' + shortDay + '</span>';
});

fiddle

Harpreet Singh
  • 2,651
  • 21
  • 31