How to convert value to Javascript string
Description
There are two ways to convert a value into a string.
- toString() method from each value
- String() cast function
toString()
toString() method returns the string equivalent of the value.
The toString()
method is available on values
that are numbers, Booleans, objects, and strings.
If a value is null or undefined, this method is not available.
var age = 11;
var aString = age.toString(); //the string "11"
var found = true;
var anotherString = found.toString(); //the string "true"
// w w w . jav a 2 s .co m
console.log(anotherString);
The code above generates the following result.
Number toString()
toString() on a number value accepts a single argument: the radix.
By passing in a radix, toString() can output the value in binary, octal, hexadecimal, or any other valid base:
var num = 10;
console.log(num.toString()); //"10"
console.log(num.toString(2)); //"1010"
console.log(num.toString(8)); //"12"
console.log(num.toString(10)); //"10"
console.log(num.toString(16)); //"a"
/*from w w w . j av a 2 s . com*/
The default is the same as providing a radix of 10.
The code above generates the following result.
String()
String()
casting function is useful for null or undefined value.
The String()
function follows these rules:
Value | Returns |
---|---|
value with toString() method | called toString without arguments |
null | "null" string |
undefined | "undefined" string |
Example:Four values are converted into strings: a number, a Boolean, null, and undefined. The result for the number and the Boolean are the same as if toString() were called.
var value1 = 10;
var value2 = true;
var value3 = null;
var value4;
/*from ww w . ja v a 2 s . c o m*/
console.log(String(value1)); //"10"
console.log(String(value2)); //"true"
console.log(String(value3)); //"null"
console.log(String(value4)); //"undefined"
Because toString() isn't available on "null" and "undefined", the String() method simply returns literal text for those values.
You can convert a value to a string by adding an empty string ("") to that value using the plus operator.
The code above generates the following result.