简体   繁体   中英

Javascript regex replace all non currency characters

I need to replace all non numeric characters in a textare using javascript. Our client wants to remove and non digits eg 1,330.00 becomes 1330.00.

I can replace all non digits except for the decimal place, but this allows multiple decimal places.

I have a jsbin of the code http://jsbin.com/vetedeca/1/edit?html,output

$(document).ready(function(){
        $('input').bind('keyup', function() {
          var value = $(this).val()

          value = value.replace(/[^\d\.]+/g,'');

          $(this).val(value);
        })
      })

How can i edit this to remove all non digits except the first occurrence of a decimal place

eg 1,330.00 becomes 1330.00 1,330.00.00 becomes 1330.00 133o.00d.33 becomes 133.00

您可以使用以下替换:

var repl = s.replace(/^(.+?\.\d+).+/g, "$1").replace(/[^\d.]+/g, "");

I managed to find a way to deal with the multiple dots issue.

I added another line using .replace() :

$(document).ready(function(){
  $('input').bind('keyup', function() {
  var value = $(this).val()

  value = value.replace(/[^\d\.]+/g,'');
  value = value.replace(/(\..*)\./g,'$1');
  $(this).val(value);
  })
})

This additional line will check if there is a first dot followed by digits, and then followed by another dot.

If it is the case, the replace will keep the existing decimal part and remove the second dot.

Updated jsbin : http://jsbin.com/vetedeca/3/edit?html,output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM