JavaScript String Methods

Strings are sequences of characters. JavaScript has many built-in methods for inspecting, extracting, and transforming them.

One important thing to know upfront: strings are immutable. String methods always return a new string. They never modify the original.

const name = 'Anna';
const upper = name.toUpperCase();

console.log(name);  // Anna (unchanged)
console.log(upper); // ANNA (new string)

Template literals

Before the methods, a quick note on template literals. They are the modern way to build strings. Use backticks instead of quotes.

const name = 'Anna';
const age = 28;

// Concatenation (old way)
const msg1 = 'Hello, ' + name + '. You are ' + age + ' years old.';

// Template literal (modern way)
const msg2 = `Hello, ${name}. You are ${age} years old.`;

You can put any JavaScript expression inside ${}.

const price = 9.99;
const qty = 3;
console.log(`Total: $${(price * qty).toFixed(2)}`); // Total: $29.97

Template literals also support multi-line strings without escape characters.

const html = `
  <div class="card">
    <h2>${name}</h2>
    <p>Age: ${age}</p>
  </div>
`;

Inspecting strings

length

Returns the number of characters in the string.

const word = 'Hello';
console.log(word.length); // 5

includes(str)

Returns true if the string contains the given text, false otherwise. Case-sensitive.

const email = 'anna@example.com';
console.log(email.includes('@'));        // true
console.log(email.includes('gmail'));    // false

startsWith(str) and endsWith(str)

Check if a string starts or ends with a given value.

const filename = 'report-2026.pdf';
console.log(filename.startsWith('report')); // true
console.log(filename.endsWith('.pdf'));      // true
console.log(filename.endsWith('.docx'));     // false

indexOf(str)

Returns the position (index) of the first match, or -1 if not found.

const sentence = 'The quick brown fox';
console.log(sentence.indexOf('quick')); // 4
console.log(sentence.indexOf('cat'));   // -1

Extracting parts

slice(start, end)

Extracts a portion of the string from start up to (but not including) end. Supports negative indices, which count from the end.

const str = 'Hello, World!';
console.log(str.slice(7, 12)); // World
console.log(str.slice(-6));    // orld!  (6 characters from the end)
console.log(str.slice(0, 5));  // Hello

slice() is the preferred method. Use it instead of substring() because it handles negative indices correctly.

substring(start, end)

Similar to slice(), but does not support negative indices.

const str = 'Hello, World!';
console.log(str.substring(0, 5)); // Hello

at(index)

Returns the character at the given index. Supports negative indices (-1 for the last character).

const str = 'Hello';
console.log(str.at(0));  // H
console.log(str.at(-1)); // o (last character)

This is cleaner than str[str.length - 1] for accessing from the end.

Transforming strings

toUpperCase() and toLowerCase()

Convert the string to all uppercase or all lowercase.

const name = 'Anna Smith';
console.log(name.toUpperCase()); // ANNA SMITH
console.log(name.toLowerCase()); // anna smith

trim(), trimStart(), and trimEnd()

Remove whitespace from both ends, the start, or the end.

const input = '   hello world   ';
console.log(input.trim());      // 'hello world'
console.log(input.trimStart()); // 'hello world   '
console.log(input.trimEnd());   // '   hello world'

trim() is useful for cleaning up user input from forms.

replace(search, replacement)

Replaces the first match.

const str = 'Hello, World! Hello!';
console.log(str.replace('Hello', 'Hi')); // Hi, World! Hello!

Pass a regular expression with the g flag to replace all matches, or use replaceAll().

replaceAll(search, replacement)

Replaces every occurrence. Added in ES2021.

const str = 'Hello, World! Hello!';
console.log(str.replaceAll('Hello', 'Hi')); // Hi, World! Hi!

repeat(count)

Returns the string repeated a given number of times.

console.log('ha'.repeat(3));  // hahaha
console.log('-'.repeat(20));  // --------------------

padStart(length, char) and padEnd(length, char)

Pad a string to a target length, adding characters to the start or end.

const id = '42';
console.log(id.padStart(6, '0')); // 000042

const label = 'Left';
console.log(label.padEnd(10, '.')); // Left......

Useful for formatting output so values line up.

Splitting strings

split(separator)

Splits the string into an array using the separator you specify.

const csv = 'Alice,Bob,Charlie,Dave';
const names = csv.split(',');
console.log(names); // ['Alice', 'Bob', 'Charlie', 'Dave']

const sentence = 'Hello World';
const words = sentence.split(' ');
console.log(words); // ['Hello', 'World']

Split into individual characters by passing an empty string:

console.log('hello'.split('')); // ['h', 'e', 'l', 'l', 'o']

split() returns an array. Use Array.join() to go the other direction: combine an array back into a string.

const words = ['Hello', 'World'];
console.log(words.join(' ')); // Hello World

Chaining methods

You can chain multiple methods together. Each one runs on the result of the previous.

const rawInput = '  Hello, World!  ';
const cleaned = rawInput.trim().toLowerCase().replace(',', '');
console.log(cleaned); // hello world!

Common mistakes

Expecting methods to modify the original string:

let greeting = 'Hello';
greeting.toUpperCase(); // does nothing to greeting

greeting = greeting.toUpperCase(); // correct: reassign the result
console.log(greeting); // HELLO

Using substring() with negative values: substring() treats negative indices as 0. Use slice() if you need to count from the end.

const str = 'Hello';
console.log(str.substring(-3)); // Hello (negative becomes 0)
console.log(str.slice(-3));     // llo (last 3 characters)

See the Arrays section: split() produces arrays, and many string operations work alongside array methods.