How to convert value to a string in JavaScript
- How to convert value to a string in JavaScript
- Using
toString()
method - Using template string literal
- Using
JSON.stringfy()
method - Using
String()
constructor
- Using
The Java programmers know to call toString()
method in order to convert any value to string. That is also the case with JavaScript.
Using toString()
method
const balance = 910const notification = 'You owe me ' + balance.toString(1)console.log(notification) // You owe me 910
toString()
also accepts an argument to represent the numeric values with respect to a base. Please refer the docs to make a better use of it.
Since the ES6
standard, we have another way as well, called template string literals.
Using template string literal
const balance = 910const notification = `You owe me ${balance}!`console.log(notification) // You owe me 910!
Looks good is it not ^_^
Prefer template strings whenever constructing strings with values or object references.
Using JSON.stringfy()
method
const balance = 910const notification = 'You owe me ' + JSON.stringify(balance)console.log(notification) // You owe me 910
This really comes handy for objects in order to print the object structure in string notation. JSON.stringfy
accepts two more arguments called replacer
and space
respectively.
Prefer to supply
space
argument when stringfying objects. Refer docs for more.
Using String()
constructor
const balance = 910const notification = 'You owe me ' + new String(balance)console.log(notification) // You owe me 910
There is this constructor
option for us to be OOPs.
Use
String()
without thenew
keyword to get string literal instead. We can verify the same withtypeof
operator as well.
const stringObject = new String('AshKeys')console.log(typeof stringObject) // objectconst stringLiteral = String('AshKeys')console.log(typeof stringLiteral) // stringconsole.log(stringObject == stringLiteral) // trueconsole.log(stringObject === stringLiteral) // false
As you can see, stringObject
is value equals with stringLiteral
, but does not strict equals it.