Reputation: 9
So I want to add items to my list by entering a value and clicking the button. I have managed to ignore empty user input but I can't figure out how to exclude spaces as user input? I can't use a conditional since the number of spaces a user enters is unpredictable.
<input id="userinput" type="text" placeholder="Enter items">
<button id="add">Click Me!</button>
<ul id="list">
<li>pen</li>
<li>pencil</li>
<li>paper</li>
</ul>
<script>
var input = document.getElementById("userinput");
var button = document.getElementById("add");
var ul = document.querySelector("ul");
button.addEventListener("click", function(){
if (input.value.length > 0) {
var li = document.createElement("li")
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
}
} )
</script>
Upvotes: 0
Views: 331
Reputation: 4755
To remove spaces at the beginning or/and end of a string, use str.trim()
, to remove all spaces, use a regex with str.replace
:
str.replace(/( )/g, "");
Upvotes: 3