Javascript toString Function can be used for different types of string conversions such as toString function can be used to convert the number or integer to string, you can convert decimal to hex, convert decimal to binary, convert decimal to octal numeral system. Javascript toString function can also convert the Boolean value to string and array items to string value. Here we will try all these Javascript sample codes of string conversions using toString function.
Syntax of Javascript toString Function
object. toString(); object. toString([radix Base]);
You can pass the optional parameter as radix base to the toString function to convert the decimal number to another base. You can also use the String object of Javascript to access the toString function. Javascript objects like array, Boolean can also access the toString function.
Example of Javascript Convert Decimal Number using toString Function
var dec = new String();
dec = 200;
document.write("Convert Decimal to Hex: = <b>" + dec.toString(16) + "</b><br /><br />");
document.write("Convert Decimal to Binary: = <b>" + dec.toString(2) + "</b><br /><br />");
document.write("Convert Decimal to Octal: = <b>" + dec.toString(8) + "</b><br /><br />");
Output
Convert Decimal to Hex: = c8
Convert Decimal to Binary: = 11001000
Convert Decimal to Octal: = 310
Example of Javascript Convert Boolean to String
var bool = new Boolean(true);
document.write("Convert Boolean to String: = <b>" + bool.toString() + "</b><br /><br />");
Output
Convert Boolean to String: = true
Example of Javascript Convert Array to string using toString Function
var arr = new Array();
arr[0] = "item 1";
arr[1] = "item 2";
arr[2] = "item 3";
document.write("Convert Array to String: = <b>" + arr.toString() + "</b> <br /><br />");
Convert Array to String: = item 1,item 2,item 3
Also read the tutorial: JavaScript String Object Functions-1 to learn about other string functions.