Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect string which contains only spaces?

Tags:

javascript

A string length which contains one space is always equal to 1:

alert('My str length: ' + str.length); 

The space is a character, so:

str = "   "; alert('My str length:' + str.length); // My str length: 3 

How can I make a distinction between an empty string and a string which contains only spaces? How can I detect a string which contain only spaces?

like image 244
Luca Avatar asked Apr 21 '12 18:04

Luca


People also ask

How do you check if string is empty or has only spaces in it python?

Using isspace() isspace() function of string class returns True if string contains only white spaces. So we can use this to check if string is empty or contain white spaces only i.e.

How do I find a space character in a string?

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.

How do you check if string is empty with spaces?

In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null.

How check string contains only space in PHP?

PHP | ctype_space() Function A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.


1 Answers

To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:

var str = "    ";  if (!str.replace(/\s/g, '').length) {    console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');  }
like image 183
Rory McCrossan Avatar answered Oct 08 '22 17:10

Rory McCrossan