Skip to content

Instantly share code, notes, and snippets.

@fyulistian
Created July 16, 2018 10:24
Show Gist options
  • Save fyulistian/efebd616838a278f866bd09e16f23584 to your computer and use it in GitHub Desktop.
Save fyulistian/efebd616838a278f866bd09e16f23584 to your computer and use it in GitHub Desktop.
Return returning only number by javascrip with regex
// 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