Strings & String Methods

Published by Brayan K

Usernames, search queries, file paths, JSON, URLs, messages — almost everything a program touches arrives as text. Mastering strings is mastering the most common job in real-world code: cleaning, slicing, searching, and reshaping words.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Keep the result of cleaning text

A parcel identifier arrives with spaces around it. Calling a method can produce the cleaned text without changing the original value. The important decision is which result you keep and use in the following operation.

const raw = "  pk-017  ";
raw.trim();
console.log(JSON.stringify(raw));
const clean = raw.trim();
console.log(JSON.stringify(clean));
console.log(clean.toUpperCase());

// ✅ Expected output:
// "  pk-017  "
// "pk-017"
// PK-017

trim() removes whitespace from both ends and returns a string. The standalone call discards that returned value. JSON.stringify makes the surrounding spaces visible inside quotes, so this example does not rely on judging invisible whitespace by eye. Uppercasing produces another string; it does not rewrite clean.

For these example parcel IDs, uppercase is a chosen storage convention. It is not a universal way to normalize people’s names, passwords or every identifier. Choose transformations according to the data’s rules, not because a chain of methods looks tidy.

const raw = "  pk-017  ";
const parcelId = raw.trim().toUpperCase();
console.log(parcelId);
console.log(JSON.stringify(raw));

// ✅ Expected output:
// PK-017
// "  pk-017  "

Read the chain left to right: the result of trim becomes the value on which toUpperCase is called. If you need to inspect an intermediate result while debugging, assign it to a named variable and log that variable.

Strings cannot be edited through an index

"use strict";
let label = "pack";
label[0] = "P";
console.log(label);

// ✅ Expected error:
// TypeError: Cannot assign to read only property '0' of string 'pack'

The explicit strict-mode directive makes this failed write throw. In a non-strict script, the same assignment can be ignored silently; the text still does not change. Reassigning a let binding to a newly built string is different from mutating the characters of the old string.

let label = "pack";
label = "P" + label.slice(1);
console.log(label);

// ✅ Expected output:
// Pack

You do not need to memorize an exception for each string method. Treat string values as immutable: use the returned text, construct new text, and assign it when your binding should change. Variables and Data Types owns the separate rules for reassigning bindings.

Index boundaries describe positions between units

const parcelId = "PK-017";
console.log(parcelId[0]);
console.log(parcelId.at(-1));
console.log(parcelId.slice(0, 2));
console.log(parcelId.slice(3));
console.log(parcelId.slice(-3));
console.log(JSON.stringify(parcelId.slice(2, 2)));

// ✅ Expected output:
// P
// 7
// PK
// 017
// 017
// ""

Indexes begin at zero. slice(start, end) includes start and stops before end, so the selected range has length end minus start for these nonnegative in-range positions. Equal boundaries select an empty string. Omitting the end continues to the string’s end. Negative slice positions count back from the end.

at(-1) accepts a negative position, while bracket access with [-1] does not mean “last.” All these positions use UTF-16 code units; the ASCII identifiers here make one unit and one visible symbol coincide. We will check the limit of that assumption below.

const code = "PK";
console.log(code[9]);
console.log(JSON.stringify(code.slice(9)));
console.log(code[-1]);
console.log(code.at(-1));

// ✅ Expected output:
// undefined
// ""
// undefined
// K

An out-of-range indexed access returns undefined, whereas an empty slice returns an empty string. If later code calls a string method on the undefined result, the failure happens there. Keep “no value at that position” separate from “a valid string containing no text.”

A match at zero is still a match

const filename = "report-final.pdf";
console.log(filename.indexOf("report"));
console.log(filename.indexOf("draft"));
console.log(filename.includes("report"));
console.log(filename.startsWith("report"));
console.log(filename.endsWith(".pdf"));

// ✅ Expected output:
// 0
// -1
// true
// true
// true

indexOf returns the starting position of the first match or -1 if there is none. Position zero is a successful match at the beginning, not an absence flag. If you only need a boolean, includes communicates that intent directly.

These searches are case-sensitive. A suffix test can check a filename convention, but it cannot prove what a file contains or whether a file is safe. Do not turn this string operation into a security guarantee.

const filename = "Report.PDF";
console.log(filename.endsWith(".pdf"));
console.log(filename.toLowerCase().endsWith(".pdf"));
console.log(filename);

// ✅ Expected output:
// false
// true
// Report.PDF

A replacement count is part of the requirement

const label = "pack--check--send";
console.log(label.replace("--", " / "));
console.log(label.replaceAll("--", " / "));
console.log(label);

// ✅ Expected output:
// pack / check--send
// pack / check / send
// pack--check--send

With the string search argument used here, replace changes the first occurrence. replaceAll changes every occurrence. Both return new strings. Choose according to the requirement: a title with one prefix to remove is a different task from a list of repeated separators. Regular-expression search arguments have additional rules; Regular Expressions Advanced Techniques owns that larger toolset.

Split follows an exact delimiter, not a word-count rule

const labels = "pack,,send";
const parts = labels.split(",");
console.log(JSON.stringify(parts));
console.log(parts.length);
console.log(parts.join(" / "));

// ✅ Expected output:
// ["pack","","send"]
// 3
// pack /  / send

The two consecutive commas have an empty field between them. split preserves that fact. Likewise, splitting a sentence on one space does not automatically handle repeated spaces, tabs or punctuation as a human word counter would. The returned value is an array, not a string; Arrays and Objects owns working with those collections.

Joining chooses the separator between entries. It does not remove empty entries. Keeping an empty field may be essential in a simple record format, so deleting it is a policy decision rather than an automatic cleanup step.

Length is not always a visible-character count

console.log("PK".length);
console.log("🙂".length);
console.log("e\u0301".length);
console.log("é".length);

// ✅ Expected output:
// 2
// 2
// 2
// 1

A string’s length counts UTF-16 code units. An emoji can occupy two units; a letter followed by a combining accent is another case where what you see is not a simple unit count. Indexing and slice use the same unit positions.

That is why reversing arbitrary text with split on an empty string is unsafe: it can separate parts of a character. Keep these operations for formats whose positions you understand. User-facing character limits or cursor behavior need a Unicode-aware policy, often based on grapheme segmentation rather than this length property.

const parcelId = "PK-017";
console.log(parcelId.length());

// ✅ Expected error:
// TypeError: parcelId.length is not a function

The number is available as parcelId.length without parentheses. The parentheses attempt to call that number as a function. In contrast, transformations such as trim and slice are methods and need a call.

Finish a label-cleaning pipeline

Retain the trimmed text first, then replace every double hyphen with a slash. Keep the original input available so a diagnostic can still show what arrived.

const raw = "  pack--check--send  ";
const clean = ___; // 👉 replace ___ with raw.trim()
const label = ___; // 👉 replace ___ with clean.replaceAll("--", "/")
console.log(label);
console.log(JSON.stringify(raw));

// ✅ Expected output:
// pack/check/send
// "  pack--check--send  "

Prepare an ASCII parcel code for display

The input is " pk-017 ". The format for this task is explicitly ASCII: two letters, a hyphen and three digits. Build an uppercase code with no surrounding whitespace. Print the cleaned code, its three-digit suffix, and whether the code begins with PK-. Finish by printing the original input with JSON.stringify, so its surrounding spaces remain visible.

const raw = "  pk-017  ";
const code = raw.trim().toUpperCase();
console.log(code);
console.log(code.slice(-3));
console.log(code.startsWith("PK-"));
console.log(JSON.stringify(raw));

// ✅ Expected output:
// PK-017
// 017
// true
// "  pk-017  "

This task transforms one input that follows the stated format. It is not a general validator for every possible parcel code. If the format can vary, define the accepted cases and failure behavior before trusting slice positions.

References: MDN’s String reference and the length property’s unit of measurement. Template Literals & Tagged Templates owns building messages with embedded expressions.

Practice quiz

What does this complete program print? const text = " PK "; text.trim(); console.log(JSON.stringify(text));

  • " PK "
  • "PK"
  • PK
  • undefined

Answer: " PK ". trim returns a new value; this call’s result was discarded.

What does this complete program print? console.log("PACK".slice(1, 3));

  • ACK
  • AC
  • CK
  • PAC

Answer: AC. The start is included and the end is excluded.

What does this complete program print? console.log("report.pdf".indexOf("report")); console.log("report.pdf".indexOf("draft"));

  • true false
  • 1 0
  • 0 -1
  • 0 0

Answer: 0 -1. A match at the beginning has position zero; no match is represented by -1.

What does this complete program print? console.log("a--b--c".replace("--", "/"));

  • a/b/c
  • a--b/c
  • a--b--c
  • a/b--c

Answer: a/b--c. A string search argument to replace changes only the first occurrence.

What does this complete program print? console.log(JSON.stringify("a,,b".split(",")));

  • ["a","","b"]
  • ["a","b"]
  • ["a",",","b"]
  • a / b

Answer: ["a","","b"]. The empty field between adjacent separators remains in the array.

What does this complete program print? console.log("🙂".length);

  • 1
  • 2
  • 4
  • 0

Answer: 2. length counts two UTF-16 code units for this emoji.

What does this complete program print? console.log("PK"[-1]); console.log("PK".at(-1));

  • K K
  • P K
  • undefined K
  • undefined undefined

Answer: undefined K. Negative bracket access does not implement the indexing rule provided by at.

Which error ends this program? const text = "PK"; console.log(text.length());

  • 2
  • undefined
  • PK
  • TypeError: text.length is not a function

Answer: TypeError: text.length is not a function. length is a numeric property; attempting to call it raises TypeError.

Continue this course

Related lessons