Skip to content
Topic 9 of 16
Theory

Strings

Why it matters

Text is everywhere: names, chat messages, page addresses, passwords, search. You need to check whether a message contains a banned word, trim extra spaces in an input field, capitalise the first letter, split a string into words. For all of this strings have methods — built-in functions called with a dot: text.toUpperCase().

Length and individual characters

const word = "JavaScript";
console.log(word.length);  // 10
console.log(word[0]);      // J   — numbering starts at zero!
console.log(word[4]);      // S
console.log(word.at(-1));  // t   — at(-1): the last character
console.log(word[word.length - 1]); // t — the same, the old way

Characters are numbered from zero: a string of length 10 has numbers (indexes) from 0 to 9.

Strings are immutable: word[0] = "j" changes nothing. All methods return a new string, and the original stays the same.

Case

const city = "Dushanbe";
console.log(city.toUpperCase()); // DUSHANBE
console.log(city.toLowerCase()); // dushanbe
console.log(city);               // Dushanbe — the original didn't change

To capitalise the first letter: s[0].toUpperCase() + s.slice(1).

Searching

const text = "I learn JavaScript and HTML";
console.log(text.includes("Java"));    // true  — is the substring there
console.log(text.startsWith("I"));     // true
console.log(text.endsWith("CSS"));     // false
console.log(text.indexOf("HTML"));     // 23    — where it starts
console.log(text.indexOf("Python"));   // -1    — not found

Searching is case-sensitive: "Java".includes("java") → false. To search ignoring case, lowercase both strings.

Cutting out a piece: slice

slice(start, end) returns the part of the string from start up to end (not including it):

const s = "JavaScript";
console.log(s.slice(0, 4));  // Java
console.log(s.slice(4));     // Script — to the end
console.log(s.slice(-3));    // ipt    — the last three

Replacing, trimming, repeating

console.log("cat and cat".replace("cat", "dog"));    // dog and cat — only the first
console.log("cat and cat".replaceAll("cat", "dog")); // dog and dog — all
console.log("   hello  ".trim());                    // "hello" — no spaces at the edges
console.log("ha".repeat(3));                         // hahaha
console.log("7".padStart(3, "0"));                   // 007 — pad on the left to length 3

Split and join: split and join

const csv = "apple,banana,cherry";
const fruits = csv.split(",");
console.log(fruits);
console.log(fruits.length);
console.log(fruits.join(" + "));

Output:

["apple","banana","cherry"]
3
apple + banana + cherry

split turns a string into an array of pieces (arrays come in the next topics), and join glues an array back into a string. split("") splits into individual characters.

Going through characters

let vowels = 0;
for (const ch of "programming") {
  if ("aeiou".includes(ch)) vowels++;
}
console.log(vowels);

Output:

3

for (const ch of string) puts each character into ch in turn.

Special characters

Inside a string a backslash \ starts a special character: \n is a line break, \t is a tab, \" is a quote inside a string with the same quotes, \\ is the backslash itself.

console.log("Line 1\nLine 2");

Output:

Line 1
Line 2

How it works inside

A string is stored as a sequence of characters in the UTF-16 encoding. Comparing "a" < "b" uses character codes: "a".charCodeAt(0) → 97. That's why "Z" < "a" is true (capital letters have smaller codes), and why sorting words with letters outside the basic alphabet can be surprising.

Because strings are immutable, each method call creates a new string. If you need to "change" something in a string, the result must be saved: name = name.trim();.

Common mistakes

  1. The method doesn't change the string. name.toUpperCase(); without assignment does nothing. You need name = name.toUpperCase(); or to use the result right away.
  2. Forgot the parentheses. text.toUpperCase without () is the function itself, not the result.
  3. length() with parentheses. length is a property, not a method: text.length.
  4. Off by one in slice. The end isn't included: "abc".slice(0, 2) → "ab".
  5. replace changes only the first occurrence. For all of them — replaceAll.

Cheat sheet

What How
Length s.length
Character s[0], s.at(-1)
Case s.toUpperCase(), s.toLowerCase()
Is it there s.includes("x"), startsWith, endsWith
Where s.indexOf("x") → index or -1
Piece s.slice(from, to)
Replace s.replace(a, b), s.replaceAll(a, b)
Spaces at the edges s.trim()
Repeat, pad s.repeat(3), s.padStart(3, "0")
To an array and back s.split(","), arr.join(", ")

Initials

Easy+10 XP

Write a function initials(fullName). It receives a first and last name separated by one space and returns the initials in capital letters with dots: "anna ivanova" → "A.I.".

initials("Anna Ivanova")   → "A.I."
initials("timur rakhimov") → "T.R."

Connect the connector to solve tasks

Task code runs on your own computer — faster and more reliable than in the browser. This needs the free CodeWithMe connector app. You only connect it once.

Looking for the connector on this computer…

  1. 1
    Download the connector for your system (Windows, macOS or Linux).Download the connectorOn the download page pick the file with your system in its name, e.g. windows-amd64.
  2. 2Run it and choose a folder for your solutions. It will install Python and Node.js there by itself when needed.
  3. 3
    Enter below the 6-digit code shown in the connector window (“Code for CodeWithMe”). If the browser asks about local network access — allow it.

The connector is open source (on GitHub), works only on your computer and runs code only after you enter the pairing code.