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

后端 未结 11 1091
心在旅途
心在旅途 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);
    }
    
    0 讨论(0)
  • 2020-12-23 11:38
    //                      ^ start string 
    //                      || \s+ white space one or more times 
    //                      || || $ = end string                        
    //                      || || ||
    //                      \/ \/ \/
    
    const isAllWhiteSpace = /^\s+$/.test(myvalue)
    
    0 讨论(0)
  • 2020-12-23 11:39

    Like this...

    function isEmpty(str) {
      return str.replace(/^\s+|\s+$/g, '').length == 0;
    }
    
    0 讨论(0)
  • 2020-12-23 11:40

    This will also work:

    var text = "   ";
    text.trim().length == 0; //true
    
    0 讨论(0)
  • 2020-12-23 11:40

    yo, we can check simply bt trim, as javascript is tagged in question,

    console.log('     '.trim() === '')//check for all empty spaces
    
    console.log('     '.trim() === '')//check for all empty tabs
    
    console.log('\n \n'.trim() === '')//check for all empty enter(empty new line)
    
    console.log('         \n'.trim() === '')//check for all spaces, tabs and new line

    0 讨论(0)
  • 2020-12-23 11:48

    To find whitespace generated by JavaScript and between elements use:

    var trimmed = $.trim( $('p').text() );
    
    if ( trimmed === '' ){
        //function...
    }
    
    0 讨论(0)
提交回复
热议问题