Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

String methods

In the lesson on strings you already met length, toUpperCase(), slice() and trim(). Here are the next most useful methods: they find where a fragment is, align text and split it into parts. All string methods return a new string and leave the original unchanged.

Position of a fragment

indexOf() returns the position where a fragment starts, or -1 when it is absent. Positions, like array indexes, are counted from zero:

const email = 'anna@example.com';
 
console.log(email.indexOf('@')); // 4

lastIndexOf() finds the last occurrence. Together with slice() this lets you cut out the part before or after the found spot:

const email = 'anna@example.com';
const at = email.indexOf('@');
 
console.log(email.slice(0, at));  // anna
console.log(email.slice(at + 1)); // example.com

Single characters

A character of a string is read by its index in square brackets or with the at() method, which understands negative numbers:

const word = 'JavaScript';
 
console.log(word[0]);     // J
console.log(word.at(-1)); // t

Padding to a length

padStart() adds characters to the start of a string until it reaches the given length, and padEnd() adds them to the end. This is how numbers and columns are aligned:

console.log('7'.padStart(3, '0')); // 007
console.log('5'.padStart(2, '0') + ':30'); // 05:30

Repeating a string

repeat() repeats a string the given number of times — handy for separators and simple pictures made of characters:

console.log('-'.repeat(10)); // ----------
console.log('★'.repeat(3) + '☆'.repeat(2)); // ★★★☆☆

Splitting and joining

split() breaks a string into an array by a separator, and the array method join() glues it back. In between you can process each piece with array methods:

const sentence = 'learn javascript every day';
 
const title = sentence
  .split(' ')
  .map((word) => word[0].toUpperCase() + word.slice(1))
  .join(' ');
 
console.log(title); // Learn Javascript Every Day

Methods can be called in a chain: each next one works with the result of the previous one.

Common mistake

String comparison is case-sensitive, so 'Anna' and 'anna' are different. Before comparing user input, bring both strings to the same form:

const input = '  Anna ';
 
console.log(input === 'anna');                      // false
console.log(input.trim().toLowerCase() === 'anna'); // true

Thanks for reading!

Donate to the site — we work hard for you.