Check if a string has white space

前端 未结 7 1563
青春惊慌失措
青春惊慌失措 2020-11-30 19:41

I\'m trying to check if a string has white space. I found this function but it doesn\'t seem to be working:

function hasWhiteSpace(s) 
{
            


        
7条回答
  •  粉色の甜心
    2020-11-30 19:50

    A few others have posted answers. There are some obvious problems, like it returns false when the Regex passes, and the ^ and $ operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).

    Besides that, the issue is just a typo.

    Change this...

    var reWhiteSpace = new RegExp("/^\s+$/");
    

    To this...

    var reWhiteSpace = new RegExp("\\s+");
    

    When using a regex within RegExp(), you must do the two following things...

    • Omit starting and ending / brackets.
    • Double-escape all sequences code, i.e., \\s in place of \s, etc.

    Full working demo from source code....

    $(document).ready(function(e) { function hasWhiteSpace(s) {
            var reWhiteSpace = new RegExp("\\s+");
        
            // Check for white space
            if (reWhiteSpace.test(s)) {
                //alert("Please Check Your Fields For Spaces");
                return 'true';
            }
        
            return 'false';
        }
      
      $('#whitespace1').html(hasWhiteSpace(' '));
      $('#whitespace2').html(hasWhiteSpace('123'));
    });
    
    " ": 
    "123":

提交回复
热议问题