should not allow more than one space in between words

function stripspaces(input)
{
    input.value = input.value.replace(/\s+/gi," ");

}

I written this function. It is working but when I point the mouse pointer or moving with left arrow in between word and giving space it is jumping to the last. Can anyone give me the solution?

Upvotes: 2

Views: 3420

Answers (2)

rassoh
rassoh

Reputation: 654

I just came across the same use case. If you also want to handle copy/paste or any other way the input's value could change, use the input event:

document.addEventListener('DOMContentLoaded', function() {

  // get a reference to the input element
  const input = document.querySelector('#myInput');

  // guard clause to check if `#myInput' actually exists in the current DOM
  if(!input) return

  // Run this every time the input's value changes
  input.addEventListener('input', e => {
    // get the value
    const value = e.target.value
    // check if the value isn't exactly ' ' and ends with a space
    const hasTrailingSpace = value !== ' ' && value.charAt(value.length-1) === ' '
    // extract words, remove empty words (handles double spaces)
    const words = value.split(' ').filter(el => el !== '')
    // create the sanitized value
    let sanitizedValue = words.join(' ')
    // add a trailing space if there was one
    if( hasTrailingSpace ) sanitizedValue += ' '
    // apply the sanitized value to the input's value
    e.target.value = sanitizedValue
  })

})
<p>Try inserting double spaces now! Also try copy/paste from somewhere else</p>
<input type="text" id="myInput">

Upvotes: 0

Brian
Brian

Reputation: 2952

You can prevent the input by calling e.preventingDefault we can simply test if the space key has been pressed and if there's a space either side of the cursor then prevent entry.

document.addEventListener('DOMContentLoaded', function() {
  
  var input = document.getElementById('myInput');
  input.addEventListener('keydown', function(e){      
       var input = e.target;
       var val = input.value;
       var end = input.selectionEnd;
       if(e.keyCode == 32 && (val[end - 1] == " " || val[end] == " ")) {
         e.preventDefault();
         return false;
      }      
    });
});
<input type="text" id="myInput">

This still has the issue that it won't prevent pastes into the box with double spaces. So it may be worth still replacing multiple spaces on focus loss to be sure that the input never contains multiple contiguous spaces.

Upvotes: 3

Related Questions