Home › Learn › JavaScript › Strings and numbers

Characters and reversing

Lesson 27 of 40. Walk a string one character at a time.

Strings are iterable: for (const c of text) visits each character, text[i] reads one, text.length counts. There is no reverse on strings, so the idiom is text.split("").reverse().join("") (or [...text].reverse().join(""), which handles emoji correctly). c.charCodeAt(0) and String.fromCharCode(n) convert between characters and codes.

To test for a letter without a regular expression, compare the lower-case and upper-case forms: a character is a letter when c.toLowerCase() !== c.toUpperCase(). A regular expression, /[a-z]/i.test(c), is the usual way; the next lessons cover them.

const text = "Level";
const clean = text.toLowerCase();
console.log(clean === [...clean].reverse().join(""));   // true

Your task

Write reverseString(text), isPalindrome(text) ignoring case and every character that is not a letter, and countVowels(text) counting a, e, i, o, u in either case.

Hint 1

const letters = text.toLowerCase().replace(/[^a-z]/g, ""); return letters === reverseString(letters);

Hint 2

let n = 0; for (const c of text.toLowerCase()) if ("aeiou".includes(c)) n++;

Show the solution
function reverseString(text) {
  return [...text].reverse().join("");
}

function isPalindrome(text) {
  const letters = text.toLowerCase().replace(/[^a-z]/g, "");
  return letters === reverseString(letters);
}

function countVowels(text) {
  let n = 0;
  for (const c of text.toLowerCase()) {
    if ("aeiou".includes(c)) n++;
  }
  return n;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.