You could also do:
if (!str || !str.replace(/ /g, "")) {
// str is either empty, null, undefined or has nothing in it other than spaces
}
This also protects you if str
is null
or undefined
too.
Here's a demo using the OP's test cases:
var testStrings = ["", " ", " 1 ", " s "];
testStrings.forEach(function(str) {
var result = false;
if (!str || !str.replace(/ /g, "")) {
// str is either empty, null, undefined or has nothing in it other than spaces
result = true;
}
log('"' + str + '"' + " tests as " + result + "<br>");
});
function log(x) {
var r = document.getElementById("results");
var div = document.createElement("div");
div.innerHTML = x;
r.appendChild(div);
}
<pre id="results"></pre>