Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if a string is empty or just contains spaces

I know I can use the following to check if a string is empty in JavaScript:

 if(Message != '')

How would I check to see if a string 'Message' in this case - is empty and doesn't contain a number of spaces. eg:

 '    '

would I need to use regular expressions?

like image 305
Adam Avatar asked Nov 13 '12 01:11

Adam


People also ask

How do I check if a string is empty or only spaces in Python?

Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ' ' – Space.


1 Answers

jQuery doesn't replace Javascript. You can use:

if (Message.replace(/\s/g, "").length > 0) {
    // Your Code
}

Having said that, if you really want jQuery version, try this:

if ($.trim(Message).length > 0) {
    // Your Code
}

Or, so long as you're only targeting IE9+ and modern browsers, you can use the built in trim function.

if (Message.trim().length > 0) {
    // Your Code
}
like image 198
Chandu Avatar answered Oct 04 '22 12:10

Chandu