Check if a single character is a whitespace?

2020-05-29 13:04发布

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 only have a single character.

Isn't there a better way (concerning performance) for checking if it's a whitespace?

If I do something like this. I would miss white spaces like tabs I guess?

if (ch == ' ') {
    ...
}

标签: javascript
9条回答
forever°为你锁心
2楼-- · 2020-05-29 13:41
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.
查看更多
Summer. ? 凉城
3楼-- · 2020-05-29 13:41
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;
}
查看更多
虎瘦雄心在
4楼-- · 2020-05-29 13:42

@jake 's answer above -- using the trim() method -- is the best option. If you have a single character ch as a hex number:

String.fromCharCode(ch).trim() === ""

will return true for all whitespace characters.

Unfortunately, comparison like <=32 will not catch all whitespace characters. For example; 0xA0 (non-breaking space) is treated as whitespace in Javascript and yet it is > 32. Searching using indexOf() with a string like "\t\n\r\v" will be incorrect for the same reason.

Here's a short JS snippet that illustrates this: https://repl.it/@saleemsiddiqui/JavascriptStringTrim

查看更多
祖国的老花朵
5楼-- · 2020-05-29 13:46

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 ;)

查看更多
爷的心禁止访问
6楼-- · 2020-05-29 13:48

this covers spaces, tabs and newlines:

if ((ch == ' ') || (ch == '\t') || (ch == '\n'))

this should be best for performance. put the whitespace character you expect to be most likely, first.

if performance is really important, probably best to consider the bigger picture than individual operations like this...

查看更多
Evening l夕情丶
7楼-- · 2020-05-29 13:51

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

查看更多
登录 后发表回答