Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.
Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.
The non-concatenation route is to use the String() constructor:
var str = new String(myVar);
Of course, var str = "" + myVar;
is shorter and easier. Be aware that all the methods here will transform a variable with a value of null into "null"
. If you want to get around that, you can use ||
to set a default when a variable's value is "falsey" like null:
var str = myVar || "";
Just so long as you know that 0 and false would also result in ""
here.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String
What about
var str = (variable || "");
//or
(variable || "").toString();
Of course you'll get this for false
, undefined
and so on, too, but it will be an empty string and not "null"
String(null)
returns "null"
, which may cause problems if a form field's value is itself null
. How about a simple wrapper function instead?
function toString(v) {
if(v == null || v == undefined) {
return "";
}
return String(v);
}
Only null
, undefined
, and empty strings should return the empty string. All other falsy values including the integer 0
will return something else. Some tests,
> toString(null)
""
> toString(undefined)
""
> toString(false)
"false"
> toString(0)
"0"
> toString(NaN)
"NaN"
> toString("")
""