Learn/JavaScript/8. Strings and a small project
Lesson 8 of 15
Sign in

JavaScript, lesson 8

Strings and a small project

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.

Looking inside a string

Changing case and cleaning up

  • 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.

Exercise 1

Name badges

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

replace
  • repeat(n) repeats a string: "-".repeat(10).
  • Splitting and joining

    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.

    Lining up columns

    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.

    Comparing text

    === 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.

    Putting it together

    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.

    Further reading

    • MDN: Text formatting
    • MDN: String
    • MDN: String.prototype.padEnd

    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:

    • the name, padded on the right with dots to 12 characters,
    • the quantity followed by x (like 3x), padded on the left with spaces to 4 characters,
    • the line total (quantity times price) with two decimals, padded on the left with spaces to 8 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);            // HELLO
    const 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"));   // true
    const 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(""));        // cba
    console.log("tea".padEnd(8, ".") + "2.50".padStart(6));   // tea.....  2.50
    console.log(String(7).padStart(3, "0"));                  // 007
      ada   LOVELACE
    grace brewster hopper
    Lovelace, A.
    Hopper, G.
    apple 3 0.40
    bread 1 2.25
    apple.......  3x    1.20
    bread.......  1x    2.25
    ------------------------
    TOTAL...............3.45