Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 字符串中日期的动态上标_Jquery_Html - Fatal编程技术网

Jquery 字符串中日期的动态上标

Jquery 字符串中日期的动态上标,jquery,html,Jquery,Html,我试图动态更改字符串中出现的日期的“th”和“st”。例如,在DIV中有 2017年9月14日星期四 我想查询以查找“th”并在其上标。我发现下面的代码可以工作,但它也可以在日和月上标字符。我不确定如何只针对相邻的字符“th” $('.date').contents().filter(function() { return this.nodeType === 3; }).replaceWith(function() { return this.nodeValue.replace(

我试图动态更改字符串中出现的日期的“th”和“st”。例如,在DIV中有
2017年9月14日星期四
我想查询以查找“th”并在其上标。我发现下面的代码可以工作,但它也可以在日和月上标字符。我不确定如何只针对相邻的字符“th”

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

您尝试的正则表达式在th附近有[],这意味着t或h,这就是您得到错误结果的原因。只需更改代码中的以下行:


返回this.nodeValue.replace(/th/g,$&')

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

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

匹配四个序数中的任意一个,如果它们跟在一个数字后面,后跟任何非字母数字字符或字符串末尾:

$(函数(){
$(“按钮”)。单击(函数(){
$(“li”)。每个(函数(){
var original=$(this.text();
$(this.html(原件.replace(/(\d)(st | nd | rd | th)(\W |$)/g,“$1$2$3”);
});
});
});

  • 5月1日,星期一
  • 5月1日,星期一
  • 5月1日,星期一
  • 5月1日,星期一
  • 2017年5月1日,星期一
  • 2017年5月1日星期一至2017年5月2日星期二
  • 2017年5月2日,星期二
  • 2017年5月3日,星期三
  • 2017年5月4日,星期四
  • 2017年5月4日,星期四

运行演示
很好的解释和回答,完全符合我的需要。谢谢很高兴这有帮助。请注意,我刚刚更新了我的答案,如果日期在句子末尾(即后面跟着标点符号),前一个答案就不起作用了。