I’m implementing a function that receives an argument which it needs to convert to its string representation.
If a given object implements a toString()
method, then the function should use it. Otherwise, the function can rely on what the JavaScript implementation offers.
What I come up with is like this:
var convert = function (arg) {
return (new String(arg)).valueOf();
}
I’m not sure you even need a function, but this would be the shortest way:
function( arg ) {
return arg + '';
}
Otherwise this is the shortest way:
arg += '';
String(null)
returns – “null”
String(undefined)
returns – “undefined”
String(10)
returns – “10”
String(1.3)
returns – “1.3”
String(true)
returns – “true”
I think this is a more elegent way.
value = value+"";
All data types in JavaScript inherit a toString
method:
('hello').toString(); // "hello"
(123).toString(); // "123"
([1,2,3]).toString(); // "1,2,3"
({a:1,b:2}).toString(); // "[object Object]"
(true).toString(); // "true"
The other answers are incomplete when it comes to a JSON object passed. So I made this one and it works for all:
var getString = (o) => {
if (o !== null) {
if (typeof o === 'string') {
return o;
} else {
return JSON.stringify(o);
}
} else {
return null;
}
}
JSON.stringify(value)
Works for null, undefined, primitives, arrays and objects — basically everything.