将表格单元格中的日期模式与 jQuery 匹配

Match date pattern in table cells with jQuery

本文关键字:模式 jQuery 匹配 日期 表格 单元格      更新时间:2023-09-26

我有一个HTML表格,其中包含包含遵循特定模式的日期的单元格。当单元格包含日期时,同一列中的所有单元格都是具有相同模式的日期。如何使用 jQuery 匹配格式并返回列?下面是演示模式的示例表:

+-------+-----------+-----------------------+-----------------------+----------+
| Type  | Compiled? |    Modified (CDT)     |     Created (CDT)     | Priority |
+-------+-----------+-----------------------+-----------------------+----------+
| Fancy | yes       | Oct 18, 2013 16:17:00 | Oct 08, 2013 05:50:32 |       75 |
| Fancy | yes       | Oct 18, 2013 16:16:28 | Oct 18, 2013 15:46:05 |       75 |
| Fancy | yes       | Oct 18, 2013 16:15:25 | Oct 17, 2013 19:04:51 |       75 |
+-------+-----------+-----------------------+-----------------------+----------+

你可以尝试如下:

$('table td').filter(function () { return /.../.test($(this).html()); }).map(function () { return $(this).index(); } );

。其中/.../是与您正在寻找的日期格式匹配的正则表达式。这将返回一个列索引数组,其中包含该模式的至少一个匹配项。这不是一个唯一的列表。如果您只是在寻找一种模式,则以下正则表达式将起作用,并且绝对需要确保它是一个有效的日期......

/^'w{3}'s'd+,'s'd{4}'s'd{1,2}:'d{2}:'d{2}$/

(这将匹配 Ziptember 第 45 天的 99 点,所以也许会得到一个更好的正则表达式。

我将稍微分解一下这条密集的线,以便更好地说明事情:

date_filter = function () { return /^'w{3}'s'd+,'s'd{4}'s'd{1,2}:'d{2}:'d{2}$/.test($(this).html())}
map_td_to_index = function () { return $(this).index(); }
console.log($('table td').filter(date_filter).map(map_td_to_index));

编辑:删除了 $.unique 的错误用法,它仅适用于 DOM 元素数组。你可以使用这样的东西:

$.fn.extend({ unique: function() 
              {
                arr = $.makeArray(this);
                return $.grep(arr, function(elem, idx) 
                                   {
                                     return $.inArray(elem, arr, idx + 1) === -1;
                                   }); 
              } 
            });

然后只需在呼叫.unique()后致电map()