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条回答
We Are One
2楼-- · 2020-05-29 13:55

While it's not entirely correct, I use this pragmatic and fast solution:

if (ch.charCodeAt(0) <= 32) {...
查看更多
冷血范
3楼-- · 2020-05-29 13:59

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.

查看更多
Summer. ? 凉城
4楼-- · 2020-05-29 14:01

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');
查看更多
登录 后发表回答