parseString in JavaScript

To parse a number into a string, use the JavaScript toString() function, passing it after the number with a . (dot). toString() doesn't modify the original variable so the result will need to be stored in a new one.

 

var number = 123;

var string = number.toString();

console.log(typeof(string));
string

 

Convert an Object to a String in JavaScript

To convert an object into a string in JavaScript, we can use the JavaScript JSON.stringify() method. To demonstrate this, let's create a simple object, store it in a variable and convert it to a string.

 

var obj = {'foo':'bar'};

var string = JSON.stringify(obj);

console.log(typeof(string));
string

 

Convert a String Back to an Object in JavaScript

To convert a string back into a JavaScript object, use the JSON.parse() method like this:

 

var obj = {'foo':'bar'};

var string = JSON.stringify(obj);

var obj2 = JSON.parse(string)

console.log(obj2.foo);
bar

 

An Alternative way of Converting to Strings

Another way to convert a thing to a string in JavaScript is to use the String() function. Pass the item to convert as the first argument and store the result in a new variable.

 

var number = 123;

var string = String(number);

console.log(typeof(string));
string

 

Conclusion

Now you know two different ways of parsing a string in JavaScript.

string parse