我正在使用一个使用事件列表小部件来引入当前事件的网站。默认情况下,日期显示为序号(数字后面的st / rd / th / nd,即“5月18日”)。我想使用Javascript / jQuery从每个事件中删除这些,以便它改为''May May'。
最初我有四个单独的脚本来删除其中的每一个,但我确信必须有一个更简单的方法 - 瞧,我发现了RegEx。
已经搜索过这个网站,我偶然发现了这个现场演示:
https://regex101.com/r/pN4oG0/1
这正是我想要的,所以我将其与其他一些位相结合(在表达式之后添加/ g以便它影响.msl_event_item的所有实例)以尝试解决问题。
$(document).ready(function() {
var str = $(".msl_event_time").html();
str.replace(/(\d+)(st|nd|rd|th)/g, "$1");
console.log(str);
});
我真的认为这会起作用,我看不出它为什么不会有任何原因,但是因为我现在只是刚刚发现了RegEx并且脚本编写不是我最强的技能,我正在努力取得任何进一步的进展 - 无论我做什么,控制台只读“5月18日 - 6月8日”。
现场网站就在这里,您可以看到完整标记:
https://www.su.rhul.ac.uk/thepackhorse/events/
以下标记的简化版本:
编辑:绝对不小心把错误的课程放在这里(msl_event_item而不是msl_event_time),所以我现在有了响应!
<div class="event_item">
<dd class="msl_event_time">
18th May - 8th June
</dd>
</div>
<div class="event_item">
<dd class="msl_event_time">
7th June
</dd>
</div>
基本上,我需要一个代码来删除每个事件项的序数。 我无法更改HTML标记 - 它由内容管理系统的小部件生成。只要它使用Javascript或jQuery,代码如何工作对我来说无关紧要。
有什么想法吗?
答案 0 :(得分:0)
正在工作......
但是您没有为str
分配“新的console.log()
值!
$(document).ready(function() {
var str = $(".msl_event_time").html();
str = str.replace(/(\d+)(st|nd|rd|th)/g, "$1");
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="msl_event_time">18th May - 8th June</div>
答案 1 :(得分:0)
执行替换后,您无法使用该值执行任何操作。如果您在进行替换(<{1}})时重新分配您的字符串,您将在控制台中看到修改后的字符串。说完了......
jQuery使我们能够将回调函数传递给str = str.replace(/(\d+)(st|nd|rd|th)/g, "$1")
。执行此操作时,该回调函数的返回结果将成为集合中每个元素的新HTML:
.html()
&#13;
$(document).ready(function(){
$('.msl_event_item').html(function(_, v){
// In this callback, 'v' is the HTML that
// currently resides inside our element
return v.replace(/(\d+)(st|nd|rd|th)/g, "$1");
});
});
&#13;
答案 2 :(得分:0)
您必须重新分配字符串,然后将元素内容设置为更新的值。下面是一个冗长的版本,@George's one在这里更好,但我想解释真正的错误。字符串是不可变的。
$(document).ready(function() {
const el = $(".msl_event_item");
el.each(function() {
let str = $(this).html();
// you need to reassign to str !
str = str.replace(/(\d+)(st|nd|rd|th)/g, "$1");
$(this).html(str)
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event_item">
<dd class="msl_event_item">
18th May - 8th June
</dd>
</div>
<div class="event_item">
<dd class="msl_event_item">
7th June
</dd>
</div>
&#13;
我确定你知道如何设置元素html内容的技巧。您的代码中的错误不是将返回的值从str.replace()
重新分配给str