Basic

Strings and Text Operations

Slice, format, and manipulate text with JavaScript's string methods.

What you will see

3 apple and banana and cherry

About 3 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Slice and inspect text with built-in string methods, then check membership and position. Watch how every operation returns a fresh string without changing the original.

1

Index into a string by bracket access and slice a start:stop range where the stop index is exclusive. Then read the last two characters using a negative index.

const text = "javascript"; console.log(text[0]); console.log(text.slice(0, 4)); console.log(text.slice(-2));

Before you run it, say out loud what it will print. Then open the answer.

What it prints
j java pt
`slice(start, end)` uses a half-open range [start:stop) and negative indices count from the end. Strings are immutable, so a new string is always returned.
2

Trim whitespace from both ends, then find where a word sits and how long the phrase is. indexOf returns -1 when the text is absent.

const phrase = "the quick brown fox"; console.log(phrase.trim().length === phrase.length); console.log(phrase.includes('brown')); console.log(phrase.indexOf('brown'));

Before you run it, say out loud what it will print. Then open the answer.

What it prints
true true 10
Use `includes` for a yes/no check and `indexOf` when you need the position. It returns -1 when the substring is not present.
3

Split a comma-separated string into an array, then glue the pieces back together with a separator. The original string is never touched.

const csv = "apple,banana,cherry"; const parts = csv.split(','); console.log(parts.length); console.log(parts.join(' and '));

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 apple and banana and cherry
Both split and join are pure operations that return new strings or arrays. Repeatedly using + on large strings is O(n^2); accumulate in a list and join once.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A string is stored immutably; methods read it and return fresh strings.
1 Text literal created -> immutable object
↓
2 Method called -> reads original, builds new string
↓
3 Slice computed via indices -> new substring object
↓
4 Result assigned to a name -> replaces old binding
Why this works
Why strings are immutable

Once created, a string's characters cannot change. This lets JavaScript cache length and hash, making strings fast as object keys and safe to share. Every operation that looks like 'editing' actually allocates a new string:

let s = "cat";
s = s + "dog";   // new object, old 'cat' may be garbage collected

For building many pieces, accumulate in a list and call Array.join('') once, repeated + on large strings is O(n²).

Template literals and escaping

Backtick strings let you interpolate ${...} and span multiple lines:

const name = "Ada";
const greeting = `Hello, ${name}!`;
const block = `line 1
line 2`;

Inside ${} you can put any expression, including a function call. To print a literal backtick or ${, escape it with a backslash: \\` or \${`.

Examples

Indexing and slicing

Accessing parts of a string

const text = "javascript";
console.log(text[0]);      // j (ES2015 bracket access)
console.log(text.charAt(0)); // j
console.log(text.slice(0, 4)); // java
console.log(text.substring(4)); // script
console.log(text.toUpperCase()); // JAVASCRIPT

slice(start, end) uses [start:stop): the stop index is exclusive. Negative indices count from the end: slice(-2) returns the last two characters.

Common string methods

Handy built-in methods

const s = "  Hello World  ";
console.log(s.trim());        // 'Hello World'
console.log(s.replace('World','JS')); // '  Hello JS  '
console.log('a,b,c'.split(',')); // ['a','b','c']
console.log('-'.join(['x','y'])); // 'x-y'

Strings are immutable: every method returns a new string and never changes the original. This is why replace and slice always allocate a fresh string.

Checking and formatting

Membership and queries

const phrase = "the quick brown fox";
console.log(phrase.includes('quick'));   // true
console.log(phrase.startsWith('the'));   // true
console.log(phrase.indexOf('brown'));    // 10
console.log(phrase.length);              // 19

includes() returns a boolean, indexOf() returns -1 when absent. Use includes for checks and indexOf when you need the position.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Variables and Types
Previous Lesson
Variables and Types
Next Lesson
Control Flow: Conditionals
Control Flow: Conditionals →