String Methods
Strings have many methods. These are the ones you will use most:
const word = "banana";
console.log(word.toUpperCase());
console.log(word.includes("an"));
console.log(word.startsWith("ba"));
console.log(word.endsWith("na"));
console.log(word.replaceAll("a", "o"));
Output:
BANANA
true
true
true
bonono
toUpperCase()gives the string in capital letters.toLowerCase()does the opposite.includes(text)checks whethertextappears anywhere in the string.startsWithandendsWithcheck the beginning and the end.fileName.endsWith(".csv")is a typical use.replaceAll(old, new)replaces everyoldwithnew.
There is also trim(), which removes spaces from both ends of a string. You cannot see spaces in the output, so this example prints the length before and after:
const padded = " hi ";
console.log(padded.length);
console.log(padded.trim().length);
Output:
6
2
One rule is true for all of these methods: strings cannot be changed. A method never changes the string you call it on. It returns a new string instead:
const s = "hello";
s.toUpperCase();
console.log(s);
const up = s.toUpperCase();
console.log(up);
Output:
hello
HELLO
The call on the second line made a new string, but nothing stored it, so it was lost. Always keep the result, in a variable or by printing it.
Be careful with replace. Without "All", it replaces only the first match:
console.log("banana".replace("a", "o"));
console.log("banana".replaceAll("a", "o"));
Output:
bonana
bonono
Searches and comparisons also care about capital letters. "banana".includes("An") is false. When you check what a user typed, make both sides the same first. trim() and toLowerCase() chain well for this, because each one returns a string:
const answer = " Yes ";
console.log(answer === "yes");
console.log(answer.trim().toLowerCase() === "yes");
Output:
false
true
In the exercise, read a word, print it in capitals, check two things about it, and replace every "a" with "o".