How to check if a text is all white space characters in client side?

后端 未结 11 1171
心在旅途
心在旅途 2020-12-23 11:14

How to check if a user input text is all white space characters (space, tab, enter etc) in client side?

11条回答
  •  孤城傲影
    2020-12-23 11:36

    If you want to see if a file contains all white space or is empty, I would recommend testing the inversion and inverting the result. That way you don't need to worry about special cases around empty string.

    all whitespace is the same as no non-whitespace so:

    function isWhitespaceOrEmpty(text) {
       return !/[^\s]/.test(text);
    }
    

    If you don't want empty strings you can modify it slightly:

    function isWhitespaceNotEmpty(text) {
       return text.length > 0 && !/[^\s]/.test(text);
    }
    

提交回复
热议问题