Description
The JavaScript String method toString()
returns the string representation of a string or an object.
- It returns a new string and doesn't change the original string.
- It is commonly used to convert a string object to a primitive string.
Every JavaScript object has a toString()
method, which is internally used to represent an object as a text when needed.
Syntax
The method toString()
has the below syntax, where str
is a string.
str.toString()
Parameters
The method toString()
doesn't allow any parameters.
Result
Returns a new string from the given string, without changing the original string.
Example 1: Using the Method
The below example shows the basic usage of the method.
var str = "Hello World!";
var strObject = new String("Hello JavaScript!");
// Getting the value without the method - works the same as using the method
document.write(str); // Prints: Hello World!
// Getting the value of a string
document.write(str.toString()); // Prints: Hello World!
// Getting the value of a string object
document.write(strObject.toString()); // Prints: Hello JavaScript!
Output:
Hello World!
Hello World!
Hello JavaScript!
Overall
The JavaScript String method toString()
returns the string representation of a string or an object.