The toString() method of the String class in JavaScript returns a string representing the specified object. This method overrides the Object.prototype.toString() method.
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.
String.toString() returns value of type String
.
In JavaScript, the toString()
method can be used to get the string representation of a string object.
For example,
strObj
using the String
constructor with the value 'Hello'
.toString()
method to get the string representation of the object.str
.str
to the console using the console.log()
method.const strObj = new String('Hello');
const str = strObj.toString();
console.log(str);
Hello
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,
str
with the value 'Hello World'
.toString()
method to get the string representation, although it will remain unchanged.result
.result
to the console using the console.log()
method.const str = 'Hello World';
const result = str.toString();
console.log(result);
Hello World
In JavaScript, the toString()
method can be used to get the string representation of a string containing special characters.
For example,
str
with the value 'Hello\nWorld'
which contains a newline character.toString()
method to get the string representation.result
.result
to the console using the console.log()
method.const str = 'Hello\nWorld';
const result = str.toString();
console.log(result);
Hello World
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.