2010-07-23 328 views
3
<form id="form1" method = "post"> 
Text1:<input type ="text" id="textname1"/><br> 
<input type ="button" name="button2" id="button2" value="UPDATE"> 
</form> 

<script type ="text/javascript"> 
    $(document).ready(function() { 
     $("#button2").click(function(e){ 
     alert($("#textname1").attr('value').replace('-','')); 
      }); 
     $("#textname1").datepicker(); 
     $("#textname1").datepicker("option", "dateFormat", 'yy-mm-dd'); 

    }); 
</script> 

假設我在字段中輸入日期2010-07-06。當我單擊button2時,我得到的警報爲201007-06.How can replace the last連字符( - )替換字符串中一個字符的多個實例

回答

7

更改您的替換函數的正則表達式參數以包含g標誌,表示「全局」。這將取代每一次發生,而不僅僅是第一次。

$("#textname1").attr('value').replace(/-/g,'') 
+0

當我更換IAM消力越來越日期爲「2010-07-07'.I要替換連字符 – Someone 2010-07-23 16:11:02

+0

@Someone:你必須刪除從正則表達式引號:'。替換(/ -/g,''))' – 2010-07-23 16:11:38

+0

@someone嘗試使用正確的示例 – 2010-07-23 16:12:10

0

你需要使用一個全球性的正則表達式,正則表達式/的和g之間在結束意味着全球所以你的情況:

"2010-07-06".replace(/-/g,'') 

將刪除所有破折號。所以,你的代碼就變成了:

$(document).ready(
function() { 
    $("#button2").click(function(e){ 
     alert($("#textname1").attr('value').replace(/-/g,'')); 
    }); 
    $("#textname1").datepicker(); 
    $("#textname1").datepicker("option", "dateFormat", 'yy-mm-dd'); 
}); 
相關問題