Insert a space after a specific character in javascript string

I am working on a form and I would like to mask the input of phone numbers. The plugins that I found are not suitable for me, as the area code can be 1 or 2 characters long. I would like to do the following: when the user enters his number after the first two characters, the script inserts a space in keyup, then after the next three and subsequent after every fourth character. Therefore, when someone types 44444444444, then 44 44 444 4444 appears in the text box. I also need to check the second group, and when someone there, for example, 1, the number should look like this: 44 1 444 4444

Is there any solution for this?

0
source share
2 answers

You can do something like this:

http://jsfiddle.net/ffwAA/4/

What applies this function to a string to obtain the desired formatting:

function formatCode(str){ var result = str; str = str.replace(/\D+/g, ""); var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/); if(m){ result = m[1] + " "; if(m[2]) result += m[2] + " "; if(m[3]) result += m[3] + " "; if(m[4]){ result += m[4].split(/(\d{4})/).join(" "); result = result.replace(/\s+/g, " "); } } return result; } 

And using this jQuery to configure it:

 function update(obj){ var val = obj.value; var got = formatCode(val); if(got != val) obj.value = got; } var timer; var prev_val = ""; $('#code').keyup(function(){ clearTimeout(timer); // when adding numbers at the end of input, update at once // don't want to update when editing in the middle of the string or removing parts of it // because it would move the carret location to the end of input, and make it unusable if(this.value.indexOf(prev_val) == 0){ update(this); prev_val = this.value; return; } prev_val = this.value; // in other cases update 1 second after the changes are done timer = setTimeout(update, 1000, this); }); 
+3
source

Have you tried the maskedInput plugin?

http://digitalbush.com/projects/masked-input-plugin/

I think it can solve your problem.

Hope this helps. Greetings

+2
source

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


All Articles