'IsNullOrWhitespace' in JavaScript?

后端 未结 8 985
-上瘾入骨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:46

    For a succinct modern cross-browser implementation, just do:

    function isNullOrWhitespace( input ) {
      return !input || !input.trim();
    }
    

    Here's the jsFiddle. Notes below.


    The currently accepted answer can be simplified to:

    function isNullOrWhitespace( input ) {
      return (typeof input === 'undefined' || input == null)
        || input.replace(/\s/g, '').length < 1;
    }
    

    And leveraging falsiness, even further to:

    function isNullOrWhitespace( input ) {
      return !input || input.replace(/\s/g, '').length < 1;
    }
    

    trim() is available in all recent browsers, so we can optionally drop the regex:

    function isNullOrWhitespace( input ) {
      return !input || input.trim().length < 1;
    }
    

    And add a little more falsiness to the mix, yielding the final (simplified) version:

    function isNullOrWhitespace( input ) {
      return !input || !input.trim();
    }
    

提交回复
热议问题