gpt4 book ai didi

jquery - 字符串中日期的动态上标

转载 作者:行者123 更新时间:2023-12-01 07:43:15 25 4
gpt4 key购买 nike

我正在尝试动态更改字符串中出现的日期的“th”和“st”。例如在 DIV 中有 <div class="date">Thursday, September 14th 2017</div>我想查询找到“th”并为其上标。我发现下面的代码可以工作,但它也可以在日期和月份中添加上标字符。我不确定如何仅针对彼此相邻的字符“th”。

$('.date').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace(/[th]/g, '<sup>$&</sup>');
});

http://jsfiddle.net/QTfxC/133/

最佳答案

您需要支持四种不同的序数:stndrdth

您可能不希望日期的小写单词部分带有上标(例如 monday、thursday),并且日期可能位于末尾字符串或后跟标点符号等。

匹配四个序数中的任何一个,当它们跟随数字并且后跟任何非字母数字字符或字符串末尾时:

$(function() {
$("button").click(function() {
$("li").each(function() {
var original = $(this).text();
$(this).html(original.replace(/(\d)(st|nd|rd|th)(\W|$)/g, "$1<sup>$2</sup>$3"));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Monday, May 1st</li>
<li>Monday, May 1st!</li>
<li>Monday, May 1st.</li>
<li>Monday, May 1st&nbsp;</li>
<li>Monday, May 1st 2017</li>
<li>Monday, May 1st 2017 until Tuesday, May 2nd 2017</li>
<li>Tuesday, May 2nd 2017</li>
<li>Wednesday, May 3rd 2017</li>
<li>Thursday, May 4th 2017</li>
<li>thursday, May 4th 2017</li>
</ul>

<button>Run Demo</button>

TL;DR replace(/(\d)(st|nd|rd|th)(\W|$)/g, "$1<sup>$2</sup>$3")

关于jquery - 字符串中日期的动态上标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com