更改html标记或其子标记(而不是其属性)文本中的日期格式

Change date format within the text of a html tag or its children (and not their attributes)

本文关键字:文本 日期 格式 属性 html 更改      更新时间:2023-09-26

我需要使用javascript重新格式化一些日期。我最初的尝试是:

var re = /('d{4})-('d{2})-('d{2})/g;
$('.container td').each(function() {
  $(this).html($(this).html().replace(re, '$3-$2-$1'));
});

但它也(自然地)更改了任何子级的html标记中的日期(如"value"属性)。如何将其重新格式化为只检查任何标记之外的文本?

使用text()而不是html()

var re = /('d{4})-('d{2})-('d{2})/g;
$('.container td').each(function() {
  var tdText = $(this).text;
  //Only repleace the match element
  if(tdText.match(re)){
      $(this).text(tdText.replace(re, '$3-$2-$1'));
  }
});