JavaScript, lesson 8
Text is everywhere: names, commands, file lines. JavaScript strings come with a large toolbox of methods. One rule underlies all of them: strings are immutable. A method never changes the original string; it returns a new one that you must store or print.
toUpperCase() / toLowerCase() change case. Lower-casing both sides is the usual way to
compare text without caring about case.trim() removes whitespace at both ends; trimStart() and trimEnd() do one side.replaceAll("a", "b") replaces every match; only replaces the first.2 exercises to try what you just read.
replacerepeat(n) repeats a string: "-".repeat(10).split turns a string into an array, and join turns an array back into a string. Together
with array methods, they solve many text tasks:
The spread [..."abc"] turns a string into an array of characters, which is a neat way to
reverse it.
padStart(width, fill) and padEnd(width, fill) add characters until the string reaches a
width. They are perfect for tables and receipts:
Notice String(7): padding is a string method, so numbers must be converted first.
toFixed already returns a string.
=== compares strings exactly, so "Apple" === "apple" is false. To ignore case, lower-case
both sides first. To put words in dictionary order, a.localeCompare(b) returns a negative
number, zero or a positive number, which you will use for sorting in a later lesson.
One subtlety: length counts UTF-16 code units, not visible characters. Most letters are one
unit, but many emoji are two, so "👍".length is 2. Spreading with [..."👍"] splits by whole
characters (code points) instead, which is why it is the safer way to walk through text that
may contain emoji.
The exercises below combine reading input, loops, decisions, functions, arrays and string
formatting. Before you start coding, sketch the steps in comments: read and split the input,
process each line, keep running totals, then print. Writing small helper functions such as
formatMoney(x) keeps the main loop readable.
Each input line holds a person's full name, typed carelessly: extra spaces and random
capitals. For each line print a badge in the form Lastname, F. where the last name is
capitalised properly (first letter upper case, the rest lower case) and F is the upper-case
first letter of the first name. Names have at least two words; ignore any middle names.
Sample input:
Sample output:
Print a shop receipt. Each input line is an item: NAME QUANTITY UNIT_PRICE, for example
apple 3 0.40. For each item print one line with:
x (like 3x), padded on the left with spaces to 4 characters,After the items, print a line of 24 - characters. Finally print TOTAL padded on the right
with dots to 12 characters, followed by the grand total with two decimals padded on the
left with dots to 12 characters. Every line is exactly 24 characters wide.
Sample input:
Sample output:
const shout = "hello";
shout.toUpperCase(); // the result is thrown away
console.log(shout); // hello
const loud = shout.toUpperCase();
console.log(loud); // HELLOconst word = "JavaScript";
console.log(word.length); // 10
console.log(word[0]); // J
console.log(word.at(-1)); // t
console.log(word.slice(0, 4)); // Java (start, up to but not including end)
console.log(word.slice(4)); // Script
console.log(word.includes("Script")); // true
console.log(word.indexOf("a")); // 1 (first match, or -1)
console.log(word.startsWith("Java")); // trueconst sentence = "the quick brown fox";
const words = sentence.split(" "); // ["the", "quick", "brown", "fox"]
const initials = words.map((w) => w[0].toUpperCase()).join("");
console.log(initials); // TQBF
console.log([..."abc"].reverse().join("")); // cbaconsole.log("tea".padEnd(8, ".") + "2.50".padStart(6)); // tea..... 2.50
console.log(String(7).padStart(3, "0")); // 007 ada LOVELACE
grace brewster hopperLovelace, A.
Hopper, G.apple 3 0.40
bread 1 2.25apple....... 3x 1.20
bread....... 1x 2.25
------------------------
TOTAL...............3.45