Regex for floating point value

I want only a floating point value in my text box and any characters and alphabetic letters are filtered out, the closest solution I found is:

jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) { $(this).val($(this).val().replace(/[^\d]/, '')); }); 

but also filters out the decimal point. how to exclude the decimal character from the specified filter or any new sentences?

0
source share
4 answers

Try the following:

 jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) { $(this).val($(this).val().replace(/[^\d.]/g, '')); }); 
+2
source

/\b[-+]?[0-9]*\.?[0-9]+\b/g or /^[-+]?[0-9]*\.?[0-9]+$/ should do the trick if you don't want to allow numbers like "1.4E-15".

http://www.regular-expressions.info/floatingpoint.html contains some suggestions for this unusual case.

+1
source
 jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) { var newVal = $(this).val().replace(/[^\d.]/, '').split("."); if ( newVal.length>2 ) newVal.length = 2; newVal.join("."); $(this).val(newVal); }); 

@Dave Newton: Only one . ..

+1
source

You need to match either not a digit or not a point, and the point must be escaped

 jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) { $(this).val($(this).val().replace(/[^\d]|[^\.]/, '')); }); 
0
source

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


All Articles