Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to excludes spaces as a user input?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading