Tale~8 min
Byte starts a newspaper
Strings, length, indexes, toUpperCase, slice, includes and template strings.
I've decided to publish a newspaper. The Byte Gazette: fish news, vacuum-cleaner gossip, the weather on the windowsill. A newspaper is text, and text in a program is strings.
JSexample
const headline = "Cat eats sausage";
console.log(headline.length);
console.log(headline[0]);
console.log(headline[headline.length - 1]);A string is written in quotes — double "…", single '…' or backticks `…`. The essentials:
text.length— how many characters it has (spaces count too);text[i]— the character at indexi, counting from zero;- strings have lots of methods — ready-made actions called with a dot.
JSexample
const headline = "Cat eats sausage";
console.log(headline.toUpperCase());
console.log(headline.slice(0, 3));
console.log(headline.includes("sausag"));
console.log(headline.replace("sausage", "fish"));What these methods do:
- toUpperCase() and toLowerCase() — change the case;
slice(start, end)— cuts out a piece: fromstartinclusive toendnot included;includes(piece)— whether that piece is inside (trueorfalse);replace(what, with)— replaces the first occurrence; replaceAll replaces all.
You can join strings with +, but template strings in backticks are handier: values are dropped right into the text with ${…}.
JSexample
const author = "Byte";
const fish = 3;
console.log("Author: " + author + ", fish eaten: " + fish);
console.log(`Author: ${author}, fish eaten: ${fish}`);Editor-in-chief's advice: if a line is full of
+ and quotes, rewrite it as a template string. Your eyes will thank you. Thank me with fish.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.
Question 1 of 3