.repeat(), .startsWith(), .endsWith()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Repeating a String
Suppose you want to display a Codémon's health bar using `"#"` blocks. Building the string with a `for` loop works, but it takes several lines of code for a very simple task:
let bar = "";
for (let i = 0; i < 5; i++) {
bar += "#";
}
console.log(bar);The `.repeat(count)` method does the exact same job in a single call: you give it a number, and it returns a new string with the original text repeated that many times:
console.log("#".repeat(5));
console.log("-".repeat(15));
console.log("Zap! ".repeat(3));Calling `.repeat(0)` returns an empty string (`""`). This is super convenient for health bars: when a Codémon reaches `0` HP, `"#".repeat(0)` naturally produces an empty bar without needing an `if` statement!
Exercise 2 — Building a Full Health Bar
By combining two `.repeat()` calls, you can build a complete gauge with both its filled blocks (`"#"`) and its empty blocks (`"-"`). Here, each block represents `10` HP out of a maximum of `50` HP:
const hp = 30;
const max = 50;
const filled = hp / 10;
const empty = (max - hp) / 10;
console.log("[" + "#".repeat(filled) + "-".repeat(empty) + "] " + hp + "/" + max);Try changing `hp` to `50` or `0` and running the code again: because `filled + empty` always equals `5` blocks, the total width of the bar never changes!
No negative numbers
`.repeat()` does not accept negative numbers and will throw an error if given one. When calculating a repeat count, always make sure it cannot drop below `0`.
Exercise 3 — Quiz: How Long?
What does this code print?
console.log("ab".repeat(3).length);6329Hint : Count the characters of the piece, then how many times it appears.
Exercise 4 — Draw the Bar
Draw a bar of 4 blocks.
Hint : One method multiplies a piece of text, and the count is already stored somewhere.
Exercise 5 — Checking the Start of a String
Suppose you are reading lines from a save file and want to check if a line begins with `"LOG:"`. The `.startsWith()` method checks whether a string begins with the exact characters you give it. It returns `true` if it does, or `false` otherwise:
const line = "LOG: Zap wins";
console.log(line.startsWith("LOG:"));
console.log(line.startsWith("Zap"));Because `.startsWith()` already returns a boolean (`true` or `false`), you can place it directly inside an `if` condition:
const line = "LOG: Zap wins";
if (line.startsWith("LOG:")) {
console.log("This is a battle log");
} else {
console.log("Unknown line");
}Exercise 6 — Checking the End of a String
The `.endsWith()` method works the same way, except it checks the end of a string. This is very useful for checking file extensions (like `".json"`) or spotting Codémon names that share the same ending (like `"chu"`):
const names = ["Aquachu", "Pyrochu", "Zap"];
names.forEach((name) => {
console.log(name + ": " + name.endsWith("chu"));
});Keep in mind that both `.startsWith()` and `.endsWith()` are case-sensitive: uppercase and lowercase letters are treated as different characters. For example, `"Aquachu"` starts with `"Aqua"`, not `"aqua"`:
const name = "Aquachu";
console.log(name.startsWith("Aqua"));
console.log(name.startsWith("aqua"));Exercise 7 — Quiz: True or False?
What does this code print?
console.log("Metachu".endsWith("chu"));truefalsechu3Hint : Look at the last characters of the word.
Exercise 8 — Quiz: Case Matters
What does this code print?
console.log("Zapchu".startsWith("zap"));falsetrueZapHint : Compare the two spellings letter by letter.
Exercise 9 — Family Check
Count how many names end with `"chu"`.
Hint : One method looks at the end of the text, and the piece to look for is written as text.
Exercise 10 — Three String Tools
Match each expression with its result.
"ab".repeat(2)"x".repeat(0)"Zapchu".startsWith("Zap")"Zapchu".endsWith("Zap")"abab"truefalseExercise 11 — Battle Display
Build the battle screen: an HP gauge for each Codémon, and a filter that keeps only the real log lines.
Step 1: `bar(hp, max)` returns a gauge like `"[###--]"`, where each block stands for 10 HP. Use one `.repeat()` for the filled part and one for the empty part. Step 2: for each Codémon, print its name, then its gauge, then `"X/Y"` with its HP and max. Step 3: print `"Logs: N"` with the number of lines in `lines` that start with `"LOG:"`. Step 4: print `"Chu family: N"` with the number of Codémon whose name ends with `"chu"`.
Expected output:
Aquachu [####-] 40/50
Zap [##---] 20/50
Logs: 2
Chu family: 1const team = [
{ name: "Aquachu", hp: 40, max: 50 },
{ name: "Zap", hp: 20, max: 50 }
];
const lines = ["LOG: start", "note: ignore me", "LOG: end"];
// Write your function here
// Use it here