How to check whether the input text field contains only white spaces?

后端 未结 3 580
感情败类
感情败类 2021-01-04 12:18

What is the easiest way to check in Javascript whether the input text field is empty (contains nothing or white spaces only)?

相关标签:
3条回答
  • 2021-01-04 12:42
    var str = document.getElementById("myInput").value;
    if (str.match(/^\s*$/)) {
        // nothing, or nothing but whitespace
    } else {
        // something
    }
    
    0 讨论(0)
  • 2021-01-04 12:50

    You are looking for something like trim function, right?

    0 讨论(0)
  • 2021-01-04 12:50

    Include this function somewhere (in order to provide a trim function)

    String.prototype.trim = function () {
       return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    };
    

    see here http://javascript.crockford.com/remedial.html

    then...

    if (document.forms['id_of_form'].elements['id_of_input'].value.trim()=='') {
        //do xyz
    }
    
    0 讨论(0)
提交回复
热议问题