Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether a string is "empty"

I need a JavaScript function to tell me whether a string object is empty. By "empty", I mean that it's not all just whitespace characters. I've written this prototype:

String.prototype.isEmpty = function() {
  return this.length === 0 || this === " " || this.test(/^\s*$/);
}

Is this alright?

Is there a more-performant version of this out there?

like image 664
CantSleepAgain Avatar asked Sep 05 '10 03:09

CantSleepAgain


People also ask

How do you check if a value is empty or not?

You can use lodash: _. isEmpty(value).

Does string isEmpty check for null?

isEmpty(< string >)​ Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.

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

Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.


1 Answers

Use

String.prototype.isEmpty = function() {  
  if (!this.match(/\S/)) {
    return ('enter some valid input.Empty space is not allowed');
  } else {
   return "correct input";
  }
}


alert("test 1:"+("    ".isEmpty()));
alert("test 2:"+("   \t ".isEmpty()));
alert("test 3:"+("  \n   ".isEmpty()));
alert("test 4:"+("hi".isEmpty()));

Note:

\s will match a whitespace character: space, tab or new line.

\S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S

like image 190
sweets-BlingBling Avatar answered Sep 22 '22 14:09

sweets-BlingBling