gpt4 book ai didi

javascript - 有没有更好的方法来编写这个 javascript 正则表达式/替换?

转载 作者:行者123 更新时间:2023-11-28 03:01:35 25 4
gpt4 key购买 nike

以下代码有效,但我确信有一种更紧凑的方法可以实现相同的结果,特别是字符串替换:

$('#nav-main .nav-sub').each(function() {

var name = $(this).attr('id');

$(this).children('li').children('a').each(function() {

var text = $(this).text().toLowerCase();
var spaces = / /g;
var sub = /sub-/;
var id = name + '-' + text.replace(spaces, '-');
var id = id.replace(sub, '');
$(this).attr('id', id);

});

});

最佳答案

$('#nav-main .nav-sub').each(function() {
var name = $(this).attr('id');
$('li a', this).each(function() {
this.id = (name + '-' + $(this).text().toLowerCase().replace(/\s/g, '-')).replace(/sub-/, '');
});
});

关于javascript - 有没有更好的方法来编写这个 javascript 正则表达式/替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/532366/

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