Given an object and the task is to convert the Object to a String using JavaScript. There are some methods to convert different objects to strings, these are:
Methods to Convert an Object to a String
This method converts the value of an object to a string.
Syntax:
String(object)
Example: In this example, we will use the string() method to convert the objects to a string.
javascript
let bool_to_s1 = Boolean(0);
let bool_to_s2 = Boolean(1);
let num_to_s = 1234;
console.log( typeof(bool_to_s1));
console.log( typeof(String(bool_to_s1)));
console.log( typeof(bool_to_s2));
console.log(typeof(String(bool_to_s2)));
console.log( typeof(num_to_s));
console.log(typeof(String(num_to_s)));
|
Outputboolean
string
boolean
string
number
string
This method converts the JavaScript object to a string which is needed to send data over the web server.
Syntax:
JSON.stringify(obj)
Example: In this example, we will use JSON.stringify() method for conversion of an object to a string.
javascript
let obj_to_str = {
name: "GeeksForGeeks",
city: "Noida",
contact: 2488
};
let myJSON = JSON.stringify(obj_to_str);
console.log(myJSON);
|
Output{"name":"GeeksForGeeks","city":"Noida","contact":2488}
Method 3: Using the plus (+) Operator with string
By default concatenation operation of a string with any data type value first, and convert the value to string type then concatenate it to string.
Syntax:
"" + object ;
Example: In this method, we will use + operate to change objects to strings.
Javascript
let obj1 = new Object();
let obj2 = { ww : 99 , ss : 22};
console.log( typeof( obj1 ));
console.log( typeof( '' + obj1));
console.log( typeof( obj2 ));
console.log(typeof( '' + obj2 ));
|
Outputobject
string
object
string
Last Updated :
20 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...