How to Detect String Which Contains Only Spaces

Check if string contains only whitespace

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

How to check for string having only spaces in javascript

Could look like

if( !currentValue.trim().length ) {
// only white-spaces

docs: trim

Even if its very self-explanatory; The string referenced by currentValue gets trimmed, which basically means all white-space characters at the beginning and the end will get removed. If the entire string consists of white-space characters, it gets cleaned up alltogether, that in turn means the length of the result is 0 and !0 will be true.

About performance, I compared this solution vs. the RegExp way from @mishik. As it turns out, .trim() is much faster in FireFox whereas RegExp seems way faster in Chrome.

Check whether a string is empty (or spaces)

You do not have a string containing only whitespace characters. You have a bytestring containing the UTF-8 encoding of a Unicode string containing only whitespace characters.

Decoding the bytes in UTF-8 produces a Unicode string that reports True for isspace:

>>> a.decode('utf-8').isspace()

but don't just slap decode('utf-8') into your code ad-hoc and hope it works.

Keep track of whether you're using Unicode or bytestrings at all times. Generally, work in Unicode, convert bytestring input to Unicode immediately, and only convert Unicode to bytestrings as it leaves your code.

If string only contains spaces?

if (strlen(trim($str)) == 0)

or if you don't want to include empty strings,

if (strlen($str) > 0 && strlen(trim($str)) == 0)

Related Topics

Leave a reply