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,

  1. We define a string object strObj using the String constructor with the value 'Hello'.
  2. We use the toString() method to get the string representation of the object.
  3. The result is stored in the variable str.
  4. We log str to the console using the console.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,

  1. We define a string variable str with the value 'Hello World'.
  2. We use the toString() method to get the string representation, although it will remain unchanged.
  3. The result is stored in the variable result.
  4. We log result to the console using the console.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,

  1. We define a string variable str with the value 'Hello\nWorld' which contains a newline character.
  2. We use the toString() method to get the string representation.
  3. The result is stored in the variable result.
  4. We log result to the console using the console.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.