Reputation: 47
I'm trying to shorten event times on a web page to only show the start time, not the start and end time. For example, if the time says:
4:30pm - 6:00pm
I want to shorten it to just:
4:30pm
The time will appear several times on the page, and sometimes it will just have the first time, like I want. I have wrapped the time in a span called .timeSpan
.
I have done some research on this site, and I found some similar examples, and tried to customize them for my purposes. I've arrived at this:
$('.timeSpan').each(function() {
var s = $(".timeSpan").text();
var n = s.indexOf(' -');
var p = s.substring(0, n != -1 ? n : s.length);
$(this).text(text.replace(s, p));
})
This does not work, however. Can anyone tell me what I'm doing wrong?
Upvotes: 0
Views: 42
Reputation: 487
.split()
is what you need.
$('.timeSpan').each(function() {
var string = $(this).text();
var times = string.split(" - ");
$(this).text(times[0]);
});
The advantage of split is that you get an array with all elements, means times[0] is the first one (start), times[1] is the next one, here the last one (end) - maybe you need it somehow else.
EDIT
The only reason why your code didn't work is because of this line:
var s = $(".timeSpan").text();
and
$(this).text(text.replace(s, p));
The first one is wrong because you dont want the content of timespan but this(within the for each). The second line is just repeated unnecessarily see this fiddle
Upvotes: 1