Text1:

Replace multiple instances of a character in a string

<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 a date in the field 2010-07-06. When I press button 2, I will get a warning like 201007-06. How can I replace the last hyphen (-)

+3
source share
2 answers

Change the regex argument of the replace function to include a flag g, which means global. This will replace every event, not just the first.

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

You need to use a global regex, the regex between / and g at the end means global, so in your case:

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

will delete all dashes. So your code will look like this:

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

Source: https://habr.com/ru/post/1756224/


All Articles