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.
http://jsperf.com/regexp-vs-trim-performance
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()
True
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
Angular2 Do Actions After Dom Has Finished Rendering
How to Pass Array Variable from View to Controller in Spring MVC
How to Specify a Single File to Be Seed Only
Customizing Item-Text in V-Select
React Native Flatlist With Clickable Items
Securityerror: Blocked a Frame With Origin from Accessing a Cross-Origin Frame
Validating Array of Different Object Shapes in Yup
How to Disable Onclick Without Altering Its Function
How to Redirect Drop Down Menu When Option Is Selected
Nosuchelementerror: Unable to Locate Element - Selenium Webdriver Using JavaScript
How to Manage Hide and Show Multiple Div and Sections Using Jquery
How to Get a Div Element from an External Webpage in HTML File
How to Compare Dates in Mongo Query
How to Separate String and Push to React State
Keep Overflow Div Scrolled to Bottom Unless User Scrolls Up
Reactjs and Images in Public Folder
Reactjs - How to Update Nested and "Normal" State Properties