2015-07-10 32 views
-1

我想知道如何更換javascript.I一個不規則的表達都試過我讀的計算器,但其還沒有成型。 我想更換所有spaces.Here +是我的代碼替換所有不規則的表情

<script> 
String.prototype.replaceAll = function(find,replace){ 
    var str= this; 
    return.replace(new RegExp(find.replace(/[-\/\\^$*?.()|[\]{}]/g, '\\$&'),'g'), replace); }; 

$(document).ready(function(){ 
    $('#myform').submit(function(){ 
     var selectedItemsText = ''; 
     $(this).find('input[type="checkbox"]:checked').each(function(){ 
      selectedItemsText += $(this).val() + '\r'; 

     }); 
      selectedItemsText=selectedItemsText.replaceAll('+',' '); 

     if (confirm("Are you sure you would like to exclude these folders(s)?"+selectedItemsText)) 
     { 
      $.ajax({ 
       type:"POST", 
       url:catalog2.php, 
       data:$('#chk[]').val(), 



        });  
      }   

      return false; 
    }); 
}); 

</script> 
+0

看看控制檯中的語法錯誤在會發生在定義'replaceAll' –

+0

你可以定義「不工作」,也許你的代碼減少到[小例子(http://stackoverflow.com/help/mcve)? –

+1

反正什麼是「不規則表達」? – evolutionxbox

回答

4

其實你可以使用一個更好的解決方案:

var rep = str.replace(/\+/g, " "); 

記住,你需要躲避+,因爲它是一個保留字。有關說明:

/\+/g 
    \+ matches the character + literally 
    g modifier: global. All matches (don't return on first match) 
1

What special characters must be escaped in regular expressions?,你應該逃避.^$*+?()[{\|外字符類和^-]\內他們

也就是說,

String.prototype.replaceAll = function(find, replace) { 
    return this.replace(
    new RegExp(
     find.replace(/[.^$*+?()[{\\|^\]-]/g, '\\$&'), 
     'g' 
    ), 
    replace 
); 
}; 
'a+b'.replaceAll('+', ' '); // "a b" 

然而,考慮短

String.prototype.replaceAll = function(find, replace) { 
    return this.split(find).join(replace); 
}; 
'a+b'.replaceAll('+', ' '); // "a b" 
相關問題