JavaScript toString

The JavaScript toString function is a String function that converts the specified expression to the string object. The basic syntax of the string toString function is

String_Object.toString()

JavaScript toString Function Example

The ToString function does not accept any arguments. The following set of examples will help you understand the JavaScript ToString function.

First we declared three variables Str1, Str2, Str3 and assigned corresponding values using the. first three statement.

The following three JavaScript statements will convert the decimal and integer values to string values

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.

<!DOCTYPE html>
<html>
<head>
    <title> ToStringJavaScript </title>
</head>
<body>
    <h1> JavaScriptToString </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>
JavaScript TOSTRING Function

JS toString Function Example 2

Here, we are using this JavaScript tostring function to convert today’s date and time to a string object.

<!DOCTYPE html>
<html>
<head>
    <title> Example  </title>
</head>
<body>
    <h1> Js 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>
Js Example

Date and Time : Fri Nov 09 2018 12:16:42 GMT+0530 (Indian Standard Time)
After toString() = Fri Nov 09 2018 12:16:42 GMT+0530 (Indian Standard Time)

This example returns the date and time of a custom date and time in a string format.

<!DOCTYPE html>
<html>
<head>
    <title> Example  </title>
</head>
<body>
    <h1> JExample </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>
JExample

Date and Time : Fri Aug 15 1947 10:15:11 GMT+0530 (Indian Standard Time)
After toString() = Fri Aug 15 1947 10:15:11 GMT+0530 (Indian Standard Time)