0

I'm trying to use jQuery to take the content of an element, truncate it by character length, then display the output in a new element. I've looked at a number of similar forum posts but can't get anything to work! What am I doing wrong here? (this is one of many attempts)

$('dd.event_time').each(function(){
    var time = $(this).text(); //Get text content from element
    var timeTrim = time.substring(0, 6);  //Truncate content after 6th character

    $(this).parent().append('<dd class="event-time-header">' + timeTrim + '</dd>'); //Wrap output in new element
});

Getting the element content works, so does the final step. It's just the .substring part I'm having problems with. I'm fairly new to jQuery by the way.

Rob
  • 4,927
  • 12
  • 49
  • 54
CaribouCode
  • 13,998
  • 28
  • 102
  • 174
  • What are you trying to truncate leading and trailing whitespace? – James Kyburz Jul 23 '12 at 14:31
  • The substring function looks correct, as long as the time is 5 or more characters long. Is it? Are you sure it is grabbing the text from the element? – Drakkainen Jul 23 '12 at 14:33
  • The date format is currently being display as a start time and end time e.g. 5:50pm - 8:20pm. I want to get rid of the end date. I figured I could limit the character length to do this. Unless there's a better method? Maybe I could tell it to only display the first word somehow? – CaribouCode Jul 23 '12 at 14:35

1 Answers1

1

That's the difference between substr and substring

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

string.substr(start[, length])

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

string.substring(indexA[, indexB])

Shikiryu
  • 10,180
  • 8
  • 49
  • 75
  • I've tried using subtr and substring in the code I originally posted. Doesn't seem to be working either way for me. – CaribouCode Jul 23 '12 at 14:40
  • @user1469087 what do you mean by "doesn't work"? Can you tell us what you obtain and what you expect? – Shikiryu Jul 23 '12 at 14:48
  • Ok I've discovered there must be something within the content management system I am using that is over-riding my Jquery. I have tested it on a locally hosted file and it's working fine there. – CaribouCode Jul 23 '12 at 15:02