How to convert an object to string using JavaScript?
Below are the methods to convert different objects to string.
Method 1: Using the function String()
The String() function converts the value of an object to a string.
Syntax:
String(object)
Parameter:
- JavaScript Object
Example :
<script> var bool_to_s1 = Boolean(0); var bool_to_s2 = Boolean(1); var num_to_s = 1234; document.write( typeof ( bool_to_s1)+ "<br>" ); document.write( typeof (String( bool_to_s1))+ "<br>" ); document.write( typeof ( bool_to_s2)+ "<br>" ); document.write( typeof (String( bool_to_s2))+ "<br>" ); document.write( typeof ( num_to_s)+ "<br>" ); document.write( typeof (String( num_to_s))+ "<br>" ); </script> |
Output:
boolean string boolean string number string
Method 2:Using JSON.stringify()
JSON.stringify() converts the javascript object to string which is needed to send data over web server.
Syntax:
JSON.stringify(obj)
Parameter:
- Can be object, array
Example:
<script> var obj_to_str = { name: "GeeksForGeeks" , city: "Noida" , contact:2488 }; var myJSON = JSON.stringify(obj_to_str); document.write(myJSON) </script> |
Output:
{"name":"GeeksForGeeks", "city":"Noida", "contact":2488}
More about JSON.stringify()