最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace multiple instances of a character in a string - Stack Overflow

programmeradmin3浏览0评论
<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>

Suppose if i enter the date in the field 2010-07-06 .When i click the button2 i get the alert as 201007-06.How can i replace the last hyphen(-)

<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>

Suppose if i enter the date in the field 2010-07-06 .When i click the button2 i get the alert as 201007-06.How can i replace the last hyphen(-)

Share edited Oct 6, 2011 at 13:44 Umber Ferrule 3,3666 gold badges37 silver badges38 bronze badges asked Jul 23, 2010 at 16:05 SomeoneSomeone 10.6k23 gold badges71 silver badges101 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Change your replace function's regular expression argument to include the g flag, which means "global". This will replace every occurrence rather than just the first one.

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

You need to use a global regular expression, the regular expression is between /'s and g at the end means global so in your case:

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

would remove all the dashes. So your code bees:

$(document).ready(
 function() {
   $("#button2").click(function(e){
      alert($("#textname1").attr('value').replace(/-/g,''));
   });
   $( "#textname1" ).datepicker();
   $( "#textname1" ).datepicker("option", "dateFormat", 'yy-mm-dd' );
});
发布评论

评论列表(0)

  1. 暂无评论