-3

I got this input type="text" and this button which shows the users input, but if the input have extra spaces, them will be showed too.How to remove these extra spaces form the input value?

var nameInput = $('#name');

function showName() {
    if (nameInput.val() === "") {
      alert('You must provide a Name');
    }
    else {
      alert('¡Hello' + ' ' + nameInput.val() + '!')
    }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<button type="button" onclick="showName()"> Show Name </button>

2 Answers2

1

Use .trim() to remove extra spaces to remove trailing and preceding spaces.

To remove any multiple occurrence of space then use .replace(/\s+/g,' ').trim();

var _name = nameInput.val().trim();
if (_name === "") {
  alert('You must provide a Name');
}
else {
  alert('¡Hello' + ' ' + _name + '!')
}
void
  • 36,090
  • 8
  • 62
  • 107
-1

You can call trim(), as in nameInput.val().trim()

Edit: Odd that i was downvoted 1 second after posting the answer. Somebody is spiteful

apoteet
  • 742
  • 5
  • 21