Home > Blockchain >  How I can add spaces before and after character on HTML input
How I can add spaces before and after character on HTML input

Time:07-28

I want to add spaces in my input field after every time when I click any symbol in my keyboard,How I can do that?

CodePudding user response:

This is an early solution that still uses the change event listening for any change occurring on the input box and that will deal with text content replacing only characters not being any letter a-zA-Z nor number 0-9 nor space.

The change event to occur requires you to switch focus to a different element. Otherwise keydown or input (as suggested in comments) was more appropriate. Anyway since the content might change in several ways, including pasting, its input must be processed in its entirety each time the event occur and you can't rely on the last character pressed only.

I used the regex replace strategy but it's still weak because your feedback was lacking.

init();

function init(){
  document.querySelectorAll('.controlled').forEach((o,i)=>{        
    o.addEventListener('change', (event)=>{    
      const subject = event.target.value;
      const result = subject.replace(/[^a-zA-Z0-9\s]/img, " $& ");
      console.log(result);
      event.target.value = result;
    });
  });  
}
.controlled{
  font-size: 20px;
  padding: .5rem;
}

.field{
  padding: 1rem;
  border: dashed 3px gray;
}
<div >
  <p>Change the value of the input box, and when you switch focus to a different element,<br> the content will be transformed so that any symbol will have added space before and after:</p>

  <input type="text" >
</div>

CodePudding user response:

You can use &ensp to insert space in HTML

  • Related