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 :
javascript
<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:
javascript
<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()
Method 3: Using plus (+) operator with string by default concatenation operation of string with any data type value JavaScript first convert the value to string type then concatenate it to string. Syntax:
"" + object ;
Example#:
Javascript
var obj1 = new Object(); var obj2 = { ww : 99 , ss : 22}; console.log( typeof ( obj1 )); console.log( typeof ( '' + obj1)); console.log( typeof ( obj2 )); console.log( typeof ( '' + obj2 )); |
Output:
object string object string