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()
Recommended Posts:
- Convert an Array to an Object in JavaScript
- Convert URL parameters to a JavaScript Object
- How to convert string into float in JavaScript?
- JavaScript | Convert a string to boolean
- Convert string into date using JavaScript
- Convert a string to an integer in JavaScript
- How to convert string to camel case in JavaScript ?
- Convert string to title case in JavaScript
- How to convert a currency string to a double value with jQuery or Javascript?
- Convert comma separated string to array using JavaScript
- JavaScript | Convert bytes to human-readable string
- How to check a JavaScript Object is a DOM Object ?
- Convert an object to associative array in PHP
- How to convert an array into object using stdClass() in PHP?
- Object.is( ) in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



