2010-07-23 289 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'); 
}); 
相关问题