• JavaScript Video Tutorials

JavaScript String toString() Method



The JavaScript String toString() method returns the string representation of the String object or primitive value on which it is called. It does not modify the original string. The JavaScript calls this method automatically when a string object is used in the context.

Syntax

Following is the syntax of JavaScript String toString() method −

toString()

Parameters

  • It does not accept any parameters.

Return value

This method returns the string value itself.

Example 1

The following example demonstrates the usage of the JavaScript String toString() method.

<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("String value(str): ", str);
   document.write("<br>The str.toString() method returns: ", str.toString());
</script>    
</body>
</html>

Output

The above program returns "Tutorials Point".

String value(str): Tutorials Point
The str.toString() method returns: Tutorials Point

Example 2

The following is another example of the JavaScript String toString() method. Here, we invoke this method on a reference variable of a String object to retrieve the value of the object. As we discussed, this method is automatically called when a String object is used (created), but if you print the reference variable value in the console, it will display as String {"value"}.

<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script>
   const strObj = new String("Hello World");
   console.log("The strObj value: ", strObj);
   // it will print String{"Hello World"};
   document.write("The strObj.toString() method returns: ", strObj.toString());
   // it will print "Hello World";
</script>    
</body>
</html>

Output

After executing the above program, it will return "Hello World".

The strObj.toString() method returns: Hello World
Advertisements