Mask latitude text field I have an input element on one of the pages. This input is supposed to take a string of digits from a user. In order to enhance UX I'd like to mask input's value at any given time. Like so:


What came up with as a solution is the following piece of code:



(function () {
  var input = document.querySelector('input');

  var state = '';

  input.addEventListener('keyup', function (e) {
    if ( e.key.match(/\d/) )     state += e.key;
    if ( e.key === 'Backspace' ) state = state.slice(0, -1);

    var degree = state.slice(0,2),
        minute = state.slice(2,4),
        second = state.slice(4,6);

    if (degree) degree += '°';
    if (minute) minute += "'";
    if (second) second += '"';

    input.value = [degree, minute, second].join(' ');
  });
})();
&lt;input type="text" /&gt;




I do not claim it to be perfect, so I very much appreciate any input.
Unless you know for sure that the degrees, minutes, and seconds are always going to be 2 digits each, this approach will cause issues. I would recommend using 3 separate inputs for each value and automatically tabbing over to the next one when the first one is filled.

If you do know they will always be 2 digits, why not just concat the value with + instead of putting them in an array and joining them?