Lesson 9 of 14 · 9 min

Working with text

Strings come with many useful methods. A few you will use constantly:

const s = "Hello, Harare";

s.length;              // 13
s.toUpperCase();       // "HELLO, HARARE"
s.toLowerCase();       // "hello, harare"
s.includes("Harare");  // true
s.indexOf("H");        // 0 (position of the first match)
s[7];                  // "H" (one character, counting from 0)
s.slice(7);            // "Harare"   from position 7 to the end
s.slice(0, 5);         // "Hello"    from 0 up to (not including) 5
s.trim();              // removes spaces at both ends

split and join

split cuts a string into an array; join glues an array back into a string:

"red,green,blue".split(",");      // ["red", "green", "blue"]
["a", "b", "c"].join("-");        // "a-b-c"
"hello".split("");                // ["h", "e", "l", "l", "o"]

Strings never change in place: every method returns a new string.

Your task

Write three functions:

  1. initials(fullName): "Tariro Moyo" gives "T.M." (always upper case).
  2. isPalindrome(word): true if the word reads the same backwards, ignoring upper and lower case.
  3. countWord(text, word): how many words in text equal word, ignoring case. Words are separated by single spaces.
main.js
function initials(fullName) {
}

function isPalindrome(word) {
}

function countWord(text, word) {
}

console.log(initials("Tariro Moyo"));
console.log(isPalindrome("Racecar"));
console.log(countWord("The cat and the hat", "the"));

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…