RCNeil
RCNeil

Reputation: 8759

Wrap date ordinal with javascript/jQuery

I have some HTML structured as such:

<span class="time">Monday, December 24th</span>
<span class="time">Tuesday, December 25th</span>
<span class="time">Monday, December 31st</span>

I cannot change the HTML output. What I would like is to wrap the date ordinal in a tag so I can style it with CSS, so it would look like:

<span class="time">Monday, December 24<sup>th</sup></span>
<span class="time">Tuesday, December 25<sup>th</sup></span>
<span class="time">Monday, December 31<sup>st</sup></span>

I cannot just find/replace in a string, because, for example, if someone put "Thursday, April 11th", the word "Thursday" contains "th". So I have to parse each string, find the numbers, and then see if a date ordinal follows them in order to wrap it in a <sup></sup> tag.

Something like this that finds the number, but how can I wrap the next two letters, rather than the number?

$('span.time').each(function() {
    $(this).html(function(i, v) {
      return v.replace(/(\d)/g, '<sup>$1</sup>');
    });
});

https://jsfiddle.net/8yao4rLu/

Any ideas?

Upvotes: 3

Views: 258

Answers (2)

msanford
msanford

Reputation: 12227

Yes: you just need two "capture groups" which are bounded by parenthesis () in the regex. You then specify what to do with each group you find.

In this case, you just re-print $1 (the number) and pop the $2 into a tag.

$('span.time').each(function() {
    $(this).html(function(i, v) {
      return v.replace(/([0-9]+)(th|st|rd|nd)/g, '$1<sup>$2</sup>');
    });
});
<span class="time">Monday, December 23rd</span> <br/>
<span class="time">Tuesday, December 24th</span> <br/>
<span class="time">Monday, December 31st</span> <br/>
<span class="time">Monday, December 2nd</span> <br/>
<span class="time">Monday, 1st of December</span>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Here is a visualization of the regular expression above:

regexper railroad diagram of regex

Upvotes: 4

charlietfl
charlietfl

Reputation: 171669

Assuming consistent formatting from server, you can do a string replace() on last 2 characters.

Using html(function) simplifies looping and accessing the exisitng content

$('.time').html(function(_, existing){
    return existing.trim().replace(/(..$)/, '<sup>$1</sup>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="time">Monday, December 24th</span>
<span class="time">Tuesday, December 25th</span>
<span class="time">Monday, December 31st</span>

Upvotes: 2

Related Questions