Tell me how you can implement input to input in this format 12 345 , 1 345 with a space?

html:

 <input type="text" name="slider"> 

Without the mask plug-in, and using:

 input.val() replace 
  • 2
  • and with one, it seems to me that it will not work, because the regulars have no idea to start from the end, and 12 345 spaces need to be inserted from the end, from the beginning it will be 123 45. - user220409

3 answers 3

I can't do it better ..

 const InputFormatType = { THOUSAND: 3 }; const decorator = ( value, format = InputFormatType.THOUSAND ) => value .split( '' ) .filter( char => char !== " " ) .reverse() .reduce( ( result, char, index ) => result += (( index >= format && index % format === 0 ? " " : "" ) + char), "" ) .split( '' ) .reverse() .join( '' ); const input = document.body.querySelector('input'); input.addEventListener('input', input_inputHandler); function input_inputHandler( { target } ){ target.value = decorator( target.value ); } 
 <input type="text"> 

  • Cool! Just did not help in my situation ask another question)) - HamSter

Found the solution .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1 " :

 var val = $('input').val(); $('input').val(val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1 ") ); $('input').change(function(){ var $this = $(this), valIn = $this.val(), valInNew = valIn.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1 "); $this.val(valInNew); }); 
 <script src="https://code.jquery.com/jquery-2.0.3.js"></script> <input type="text" value="12345"> 

  • one
    use keyup instead of change - Alex
  • @Alex, thank you, I will consider! - HamSter
  • one
    @ElenaSemenchenko That would be better - jsfiddle.net/hvbevdoj - A. Gusev
  • You just need to delete the spaces every time, otherwise it turned out like this for me - 123 456 789 123 45 6 661 and even 3 45 6 661 5 559 . - user220409

http://igorescobar.imtqy.com/jQuery-Mask-Plugin/

 $('input[name=slider]').mask('000 000 000', {reverse: true});