JavaScript String(): Convert a Value to a String

The JavaScript String() method is used to convert a specified value to a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Type Before using String() = <span id="abc"></span></p>
   <p>Type After using String() = <span id="xyz"></span></p>

   <script>
      let DateObject = new Date();
      document.getElementById("abc").innerHTML = typeof(DateObject);
      document.getElementById("xyz").innerHTML = typeof(String(DateObject));
   </script>
   
</body>
</html>
Output

Type Before using String() =

Type After using String() =

Please note: To convert a number to a string, use the Number.toString() method. However, the String() method can also be used to convert a value (a number) to a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Type Before using String() = <span id="abc"></span></p>
   <p>Type After using String() = <span id="xyz"></span></p>

   <script>
      let val = 2435;
      document.getElementById("abc").innerHTML = typeof(val);
      document.getElementById("xyz").innerHTML = typeof(String(val));
   </script>
   
</body>
</html>
Output

Type Before using String() =

Type After using String() =

JavaScript String() syntax

The syntax of the String() method in JavaScript is:

String(x)

where x refers to a value that will be converted into a string.

The String() method returns a string.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!