Check if a single character is a whitespace?

后端 未结 9 1189
清酒与你
清酒与你 2021-02-06 21:21

What is the best way to check if a single character is a whitespace?

I know how to check this through a regex.

But I am not sure if this is the best way if I onl

相关标签:
9条回答
  • 2021-02-06 21:42

    The regex approach is a solid way to go. But here's what I do when I'm lazy and forget the proper regex syntax:

    str.trim() === '' ? alert('just whitespace') : alert('not whitespace');
    
    0 讨论(0)
  • 2021-02-06 21:49
    function hasWhiteSpace(s) {
      return /\s/g.test(s);
    }
    

    This will work

    or you can also use this indexOf():

    function hasWhiteSpace(s) {
      return s.indexOf(' ') >= 0;
    }
    
    0 讨论(0)
  • 2021-02-06 21:55

    If you only want to test for certain whitespace characters, do so manually, otherwise, use a regular expression, ie

    /\s/.test(ch)
    

    Keep in mind that different browsers match different characters, eg in Firefox, \s is equivalent to (source)

    [ \f\n\r\t\v\u00A0\u2028\u2029]
    

    whereas in Internet Explorer, it should be (source)

    [ \f\n\r\t\v]
    

    The MSDN page actually forgot the space ;)

    0 讨论(0)
  • 2021-02-06 21:56

    how about this one : ((1L << ch) & ((ch - 64) >> 31) & 0x100002600L) != 0L

    0 讨论(0)
  • 2021-02-06 21:58
    var testWhite = (x) {
        var white = new RegExp(/^\s$/);
        return white.test(x.charAt(0));
    };
    

    This small function will allow you to enter a string of variable length as an argument and it will report "true" if the first character is white space or "false" otherwise. You can easily put any character from a string into the function using the indexOf or charAt methods. Examples:

    var str = "Today I wish I were not in Afghanistan.";
    testWhite(str.charAt(9));  // This would test character "i" and would return false.
    testWhite(str.charAt(str.indexOf("I") + 1));  // This would return true.
    
    0 讨论(0)
  • 2021-02-06 22:00

    I have referenced the set of whitespace characters matched by PHP's trim function without shame (minus the null byte, I have no idea how well browsers will handle that).

    if (' \t\n\r\v'.indexOf(ch) > -1) {
        // ...
    }
    

    This looks like premature optimization to me though.

    0 讨论(0)
提交回复
热议问题