在js.match(/(^ | \ s)here- \ S + / g)中使用函数中的参数

时间:2018-09-25 10:50:30

标签: javascript jquery match

通过将类前缀直接硬编码到match()中,我可以按预期工作:

(function($){
    jQuery.fn.extend({
        removePrefixClass:function(classPrefix){
            $(this).removeClass(function(index, css){
                return(css.match(/(^|\s)notice-\S+/g) || []).join(' ');
            });
        }
    });
})(jQuery);

如何将功能参数classPrefix放在match()内?

在这种情况下的用法是$(this).removePrefixClass('notice-'),以便删除名为notice-successnotice-errornotice-warning等的所有类,依此类推... < / p>

我在这里看到了一些建议使用RegExp的答案。但是似乎无法弄清楚如何在我的场景中使用它。

这是使用中的代码部分:
({/* ajax request* /> .done> if,现有#notice

$(function(){
    $("form.ajax").submit(function(e){
        e.preventDefault();
        if($('form[id]').length){  //  make sure the form has a unique id
            let $form = $('form#'+$(this).attr('id'));  //  use this specific form
            let $formNotice = $form.find('#notice');  //  locate #notice element
        /*  ajax request  */
            submitAjax($form)  //  personal wrapper function that just returns an $.ajax({...})-object
            .done(function(data,statusText,jqXHR){
                if($formNotice.length){  //  update existing notice
/*-->  */           $formNotice.removePrefixClass('notice-');   // remove class that starts with "notice-"
                    $formNotice.prependClass('notice-'+data['type']);  //  add new `notice-`class to the beginning to make it work
                    $formNotice.find('p').html(data['msg']);  //  add response message
                } else {  //  set new #notice
                    $(setNotice(data['type'],data['msg'])).hide().prependTo($form).slideDown("slow");  //  personal function that returns the `notice-`-html-element
                }
            })
            .fail(function(){
                console.log('fail : '+statusText);
            })
            .always(function(){
                console.log('always');
            });
        //
        } else {
            console.log('form is missing id');  
        }
    });
});

1 个答案:

答案 0 :(得分:0)

您需要显式构建RegExp对象,如下所示:

removePrefixClass: function(classPrefix) {
  var re = new RegExp('(^|\s)' + classPrefix + '\S+', 'g');
  $(this).removeClass(function(index, css) {
    return(css.match(re) || []).join(' ');
  });
}