Created
July 16, 2018 10:24
-
-
Save fyulistian/efebd616838a278f866bd09e16f23584 to your computer and use it in GitHub Desktop.
Return returning only number by javascrip with regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function typing always return number with regex | |
function formattedNumberField (selector = ".formattedNumberField") { | |
$(selector).on('keyup', function() { | |
/** | |
* Regular Expression. | |
* ref. | |
* https://regex101.com | |
* | |
* @type {RegExp} | |
*/ | |
var regex = /^0+/gi; // Find leading zero | |
var rgex = /\D/g; // Digits | |
var regx = /\B(?=(\d{3})+(?!\d)\.?)/g; // Formating number | |
// skip for arrow keys | |
if(event.which >= 37 && event.which <= 40) return; | |
// disable leading 0 | |
if (this.value.match(regex)) this.value = this.value.replace(regex, ''); | |
// format number | |
$(this).val(function(index, value) { | |
return value.replace(rgex,"").replace(regx, ","); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment