'IsNullOrWhitespace' in JavaScript?

后端 未结 8 986
-上瘾入骨i
-上瘾入骨i 2020-12-02 22:22

Is there a JavaScript equivalent to .NET\'s String.IsNullOrWhitespace so that I can check if a textbox on the client-side has any visible text in it?

I\'d rather do

相关标签:
8条回答
  • 2020-12-02 22:22

    It's easy enough to roll your own:

    function isNullOrWhitespace( input ) {
    
        if (typeof input === 'undefined' || input == null) return true;
    
        return input.replace(/\s/g, '').length < 1;
    }
    
    0 讨论(0)
  • 2020-12-02 22:33

    no, but you could write one

    function isNullOrWhitespace( str )
    {
      // Does the string not contain at least 1 non-whitespace character?
      return !/\S/.test( str );
    }
    
    0 讨论(0)
  • 2020-12-02 22:33

    Pulling the relevant parts of the two best answers, you get something like this:

    function IsNullOrWhitespace(input) {
        if (typeof input === 'undefined' || input == null) return true;
        return !/\S/.test(input); // Does it fail to find a non-whitespace character?
    }
    

    The rest of this answer is only for those interested in the performance differences between this answer and Dexter's answer. Both will produce the same results, but this code is slightly faster.

    On my computer, using a QUnit test over the following code:

    var count = 100000;
    var start = performance.now();
    var str = "This is a test string.";
    for (var i = 0; i < count; ++i) {
        IsNullOrWhitespace(null);
        IsNullOrWhitespace(str);
    }
    var end = performance.now();
    var elapsed = end - start;
    assert.ok(true, "" + count + " runs of IsNullOrWhitespace() took: " + elapsed + " milliseconds.");
    

    The results were:

    • RegExp.replace method = 33 - 37 milliseconds
    • RegExp.test method = 11 - 14 milliseconds
    0 讨论(0)
  • 2020-12-02 22:36

    trim() is a useful string-function that JS is missing..

    Add it:

    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,"") }
    

    Then: if (document.form.field.value.trim() == "")

    0 讨论(0)
  • 2020-12-02 22:43

    You must write your own:

    function isNullOrWhitespace(strToCheck) {
        var whitespaceChars = "\s";
        return (strToCheck === null || whitespaceChars.indexOf(strToCheck) != -1);
    }
    
    0 讨论(0)
  • 2020-12-02 22:44

    Try this out

    /**
      * Checks the string if undefined, null, not typeof string, empty or space(s)
      * @param {any} str string to be evaluated
      * @returns {boolean} the evaluated result
    */
    function isStringNullOrWhiteSpace(str) {
        return str === undefined || str === null
                                 || typeof str !== 'string'
                                 || str.match(/^ *$/) !== null;
    }
    

    You can use it like this

    isStringNullOrWhiteSpace('Your String');
    
    0 讨论(0)
提交回复
热议问题