Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.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
有没有更好的方法来编写这个javascript regex/replace?_Javascript_Jquery_Regex_Replace - Fatal编程技术网

有没有更好的方法来编写这个javascript regex/replace?

有没有更好的方法来编写这个javascript regex/replace?,javascript,jquery,regex,replace,Javascript,Jquery,Regex,Replace,以下代码可以工作,但我相信有一种更简洁的方法可以实现相同的结果,特别是字符串替换: $('#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 =

以下代码可以工作,但我相信有一种更简洁的方法可以实现相同的结果,特别是字符串替换:

$('#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-/, '');
    });
});