1
<html>
 <body>
   <input type="text" keyup="_onSearchKeyUp">
 </body>
</html>

I'm trying to get an input box to display numbers with space separator. Like this: 1234567891 and 123 456 789 10(every 3 symbols).

Im wrote this code:

        _onSearchKeyUp: function (event) {
        let value = this._getValue();
        var parts = value.split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.$input.val(parts.join("."));

But this is not a good solution to the problem. Because of the value change, i'm always end up with the marker at the end, So it is e.g. impossible to use arrow keys to navigate back or just edit in the middle of the input.

How i can fix this problem?

  • Please clarify the question. What type of input box is being used (text / number)? How is the space separator determined (every 3 numbers / replace dots / middle of the number no matter how big)? – icecub Dec 20 '20 at 13:56
  • Need one more clarification: Does the input box only accept numbers? Or does it accept all other input as well? Like if a user types: `Hello world 123456` should it become `Hello world 123 456`? – icecub Dec 20 '20 at 14:27
  • @icecub Field accept only numbers(Like this: 1234567 -> 123 456 7) – Павел Храпун Dec 20 '20 at 14:31
  • This is what I came up with: https://jsfiddle.net/8xm2vjkr/ Added optional filter for number input only. You can remove that part if you don't want it. – icecub Dec 20 '20 at 14:39
  • @WiktorStribiżew, it works, but not for me. Cause i need add listener to key up event – Павел Храпун Dec 21 '20 at 08:20
  • I recommend doing this conditionally. Check your replaced string against the original input string. Only if changed, write it back. In the latter case you need to set the cursor to the original position (or +1 if a space was added) - see https://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field/48150864#48150864 to get cursor position. – Peter Thoeny Dec 28 '20 at 01:51

1 Answers1

0
const formatString =  (str)=>str.replace( /(\S{3})/g ,'$1  ' )

the regex groups any 3 ({3}) non-space characters (\S) . The g flags makes the regex capture all matches (left to right ). The replacing value is the matchedgoup ($1 )+ 1spaceChar (' ')

yoty66
  • 390
  • 2
  • 12