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?
You can use lodash: _. isEmpty(value).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With