JavaScript String toString()
Syntax & Examples
toString() method
The toString() method of the String class in JavaScript returns a string representing the specified object. This method overrides the Object.prototype.toString() method.
Syntax of toString()
The syntax of String.toString() method is:
toString()
This toString() method of String returns a string representing the specified object. Overrides the Object.prototype.toString() method.
Return Type
String.toString() returns value of type String
.
✐ Examples
1 Using toString() method on a string object
In JavaScript, the toString()
method can be used to get the string representation of a string object.
For example,
- We define a string object
strObj
using theString
constructor with the value'Hello'
. - We use the
toString()
method to get the string representation of the object. - The result is stored in the variable
str
. - We log
str
to the console using theconsole.log()
method.
JavaScript Program
const strObj = new String('Hello');
const str = strObj.toString();
console.log(str);
Output
Hello
2 Using toString() method on a primitive string
In JavaScript, the toString()
method can be used on a primitive string, although it is usually not necessary as primitive strings are already strings.
For example,
- We define a string variable
str
with the value'Hello World'
. - We use the
toString()
method to get the string representation, although it will remain unchanged. - The result is stored in the variable
result
. - We log
result
to the console using theconsole.log()
method.
JavaScript Program
const str = 'Hello World';
const result = str.toString();
console.log(result);
Output
Hello World
3 Using toString() method on a string with special characters
In JavaScript, the toString()
method can be used to get the string representation of a string containing special characters.
For example,
- We define a string variable
str
with the value'Hello\nWorld'
which contains a newline character. - We use the
toString()
method to get the string representation. - The result is stored in the variable
result
. - We log
result
to the console using theconsole.log()
method.
JavaScript Program
const str = 'Hello\nWorld';
const result = str.toString();
console.log(result);
Output
Hello World
Summary
In this JavaScript tutorial, we learned about toString() method of String: the syntax and few working examples with output and detailed explanation for each example.