Skip to content

String formatting ​

Upper and lowercase ​

We can change the case of strings with .toUpperCase() and .toLowerCase()

js
const quote = 'The house on Mango Street isn’t it.'

console.log(quote.toUpperCase())
console.log(quote.toLowerCase())
console
THE HOUSE ON MANGO STREET ISN’T IT.
the house on mango street isn’t it.

Slice ​

Slice works with strings just the same as it works with arrays.

js
const quote = 'The house on Mango Street isn’t it.'
console.log(quote.slice(13, 25))
console
Mango Street

Template literals ​

We can interpolate values into strings using backticks ` and ${}.

js
const author = 'Min Jin Lee'
const book = 'Pachinko'
const year = 2017

const summary = `${author} wrote ${book} in ${year}`
console.log(summary)
console
Min Jin Lee wrote Pachinko in 2017

Trim ​

We can remove whitespace from the beginning and end of a string with trim()

js
const quote = '   Stay awhile and listen!   '
const trimmedQuote = quote.trim()
console.log(trimmedQuote)
console
Stay awhile and listen!

Formatting numbers ​

We can use .toFixed() to turn a number into a string with the given number of decimals.

TIP

Note that trailing 0s are included, which makes it good for formatting currency.

js
const price = 2.39782
const displayPrice = price.toFixed(2)
console.log('£' + displayPrice)
console
£2.40