The JavaScript ToString function is a String function that converts the specified expression to the string object. The basic syntax of the ToString function in JavaScript Programming Language is
String_Object.ToString()
JavaScript ToString Function Example
The following set of examples will help you understand the ToString function in JavaScript Programming Language.
TIP: The ToString function does not accept any arguments.
<!DOCTYPE html> <html> <head> <title> ToString JavaScript </title> </head> <body> <h1> JavaScript ToString </h1> <script> var Str1 = "Tutorial Gateway"; var Str2 = 123.45; var Str3 = 4567; var Str4 = Str1.toString(); var Str5 = Str2.toString(); var Str6 = Str3.toString(); document.write(Str4 + "<br \>"); document.write(Str5 + "<br \>"); document.write(Str6 + "<br \>"); document.write(typeof(Str5) + "<br \>"); document.write(typeof(Str6) ); </script> </body> </html>
First we declared three String variables Str1, Str2, Str3 and assigned corresponding values using following statement
var Str1 = "Tutorial Gateway"; //String var Str2 = 123.45; //Float var Str3 = 4567; //Integer
The following JavaScript statements will convert the decimal and integer values to string values
var Str4 = Str1.toString(); var Str5 = Str2.toString(); var Str6 = Str3.toString();
Next, We used the TypeOf Function, to show you the Data type of the variable. From the above screenshot, you can observe that the data type of Str2 (decimal) and Str3 (integer) converted to string type.
document.write(typeof(Str5) + "<br \>"); document.write(typeof(Str6) );
JS toString Function Example 2
Here, we are using this tostring function to convert today’s date and time to a string object.
<!DOCTYPE html> <html> <head> <title> JavaScript Date toString Function </title> </head> <body> <h1> JavaScript toString Example </h1> <script> var dt = Date(); document.write("Date and Time : " + dt + "<br/>"); var x = dt.toString(); document.write("After toString() = " + x); </script> </body> </html>
toString Function Example 3
This JS toString example returns the date and time of a custom date and time in a string format.
<!DOCTYPE html> <html> <head> <title> JavaScript Date toString Function </title> </head> <body> <h1> JavaScript toString Example </h1> <script> var dt = Date(1947, 7, 15, 10, 15, 11); document.write("Date and Time : " + dt + "<br/>"); var x = dt.toString(); document.write("After toString() = " + x); </script> </body> </html>