0

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>
  • Duplicate of https://stackoverflow.com/questions/5963182/how-to-remove-spaces-from-a-string-using-javascript – Mujeeb N. Nov 12 '21 at 07:19
  • How do you think use regex? let replaceTest = " 33 7 773 "; replaceTest .replace(/ /gi, ""); console.log(replaceTest ); // 337773 – Hyunjune Kim Nov 12 '21 at 07:20
  • input.value.replace(/\s/g, '') – Ravi Ashara Nov 12 '21 at 07:21
  • Does this answer your question? [How to remove spaces from a string using JavaScript?](https://stackoverflow.com/questions/5963182/how-to-remove-spaces-from-a-string-using-javascript) – malarres Nov 12 '21 at 07:35

1 Answers1

3

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, "");

GoldenretriverYT
  • 3,043
  • 1
  • 9
  • 22