#1

Get characters of a string

Topics: JavaScript

The following line returns all characters of a given string:

const message = 'Hello';
const chars = [...message]; // ['H', 'e', 'l', 'l', 'o']

If you want to get the first and the remaining characters of a string, then use ES6 destructing:

const [first, ...rest] = message;
// first = 'H'
// rest = ['e', 'l', 'l', 'o']

We can use it to capitalize or decapitalize a string:

capitalize = ([first, ...rest]) => (
`${first.toUpperCase()}${rest.join('')}`
);

decapitalize = ([first, ...rest]) => (
`${first.toLowerCase()}${rest.join('')}`
);

capitalize('hello world'); // 'Hello world'
Fix a typo or suggest an improvement
#2 Convert string to number