JavaScript String Methods: A Complete Guide with Examples

February 15, 2026 · 10 min read · Developer

Strings are one of the most fundamental data types in JavaScript. Whether you're building a web app, processing user input, manipulating URLs, or formatting data for display, you'll work with strings constantly. JavaScript provides a rich set of built-in methods for searching, extracting, transforming, and combining strings.

This guide covers every important string method you need to know, with practical examples you can use right away. We'll start with the basics and work our way up to modern ES6+ methods.

String Basics

In JavaScript, strings are immutable sequences of characters. You can create them with single quotes, double quotes, or template literals:

const single = 'Hello';
const double = "World";
const template = `Hello ${double}`;  // "Hello World"

// String length
'Hello'.length  // 5

// Accessing characters
'Hello'[0]      // "H"
'Hello'.at(-1)  // "o" (ES2022)

Strings are immutable — methods that appear to modify a string actually return a new string. The original is never changed.

Searching and Finding

includes()

Checks whether a string contains a substring. Returns true or false.

'Hello World'.includes('World')     // true
'Hello World'.includes('world')     // false (case-sensitive)
'Hello World'.includes('Hello', 1)  // false (search from index 1)

startsWith() and endsWith()

'Hello World'.startsWith('Hello')   // true
'Hello World'.endsWith('World')     // true
'report.pdf'.endsWith('.pdf')       // true — great for file extensions

indexOf() and lastIndexOf()

Find the position of a substring. Returns -1 if not found.

'Hello World Hello'.indexOf('Hello')      // 0
'Hello World Hello'.lastIndexOf('Hello')  // 12
'Hello World'.indexOf('xyz')              // -1

search()

Like indexOf() but accepts a regex:

'Hello123'.search(/\d/)    // 5 (first digit position)
'Hello'.search(/\d/)       // -1

match() and matchAll()

// match returns first match (or all with /g flag)
'Hello 123 World 456'.match(/\d+/)    // ["123"]
'Hello 123 World 456'.match(/\d+/g)   // ["123", "456"]

// matchAll returns an iterator with capture groups
const matches = 'a1 b2 c3'.matchAll(/([a-z])(\d)/g);
for (const m of matches) {
  console.log(m[1], m[2]);  // "a" "1", "b" "2", "c" "3"
}

Extracting Substrings

slice()

The most versatile extraction method. Supports negative indices.

'Hello World'.slice(6)       // "World"
'Hello World'.slice(0, 5)   // "Hello"
'Hello World'.slice(-5)     // "World"
'Hello World'.slice(-5, -1) // "Worl"

substring()

Similar to slice() but doesn't support negative indices. If start > end, it swaps them.

'Hello World'.substring(6)     // "World"
'Hello World'.substring(6, 0) // "Hello " (swapped to 0, 6)

In practice, prefer slice() — it's more predictable and supports negative indices.

Transforming Strings

toUpperCase() and toLowerCase()

'hello'.toUpperCase()  // "HELLO"
'HELLO'.toLowerCase()  // "hello"

trim(), trimStart(), trimEnd()

Remove whitespace from strings — essential for processing user input.

'  Hello World  '.trim()       // "Hello World"
'  Hello World  '.trimStart()  // "Hello World  "
'  Hello World  '.trimEnd()    // "  Hello World"

padStart() and padEnd()

Pad strings to a target length — great for formatting numbers.

'5'.padStart(3, '0')    // "005"
'42'.padStart(5, ' ')   // "   42"
'hi'.padEnd(10, '.')    // "hi........"

repeat()

'ha'.repeat(3)          // "hahaha"
'-'.repeat(40)          // "----------------------------------------"
⚡ Try it yourself: Experiment with text transformations using the Wootils Case Converter — convert text between uppercase, lowercase, title case, and more.

Replacing Content

replace()

Replaces the first match of a string or regex pattern:

'Hello World'.replace('World', 'JS')        // "Hello JS"
'aabbcc'.replace('b', 'X')                  // "aaXbcc" (first only!)
'Hello World'.replace(/world/i, 'JS')       // "Hello JS" (case-insensitive)

replaceAll()

Replaces ALL occurrences (ES2021). Before this, you had to use regex with the /g flag:

// The modern way
'aabbcc'.replaceAll('b', 'X')               // "aaXXcc"

// The old way (still works)
'aabbcc'.replace(/b/g, 'X')                 // "aaXXcc"

Splitting and Joining

split()

Splits a string into an array by a separator:

'a,b,c'.split(',')              // ["a", "b", "c"]
'Hello World'.split(' ')        // ["Hello", "World"]
'Hello'.split('')               // ["H", "e", "l", "l", "o"]
'a::b::c'.split('::')           // ["a", "b", "c"]
'a,b,c,d'.split(',', 2)        // ["a", "b"] (limit to 2)

Array.join()

The opposite of split — joins an array into a string:

['a', 'b', 'c'].join(', ')      // "a, b, c"
['2026', '02', '15'].join('-')  // "2026-02-15"
['Hello', 'World'].join(' ')    // "Hello World"

Template Literals (ES6)

Template literals (backtick strings) are one of JavaScript's best features for string work:

const name = 'World';
const greeting = `Hello, ${name}!`;  // "Hello, World!"

// Expressions inside ${}
`2 + 2 = ${2 + 2}`                   // "2 + 2 = 4"
`${name.toUpperCase()}!`             // "WORLD!"

// Multi-line strings
const html = `
  <div class="card">
    <h2>${name}</h2>
  </div>
`;

Modern String Methods (ES2020+)

at() (ES2022)

Access characters with support for negative indices:

'Hello'.at(0)    // "H"
'Hello'.at(-1)   // "o" (last character!)
'Hello'.at(-2)   // "l"

String.raw

A tagged template that returns the raw string without processing escape sequences:

String.raw`Hello\nWorld`  // "Hello\\nWorld" (no newline)
// Useful for regex and file paths
String.raw`C:\Users\Documents`

Practical String Recipes

Capitalize First Letter

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize('hello')  // "Hello"

Slugify a Title

const slugify = str => str
  .toLowerCase()
  .trim()
  .replace(/[^\w\s-]/g, '')
  .replace(/[\s_]+/g, '-');
slugify('Hello World! How are you?')  // "hello-world-how-are-you"

Truncate with Ellipsis

const truncate = (str, max) =>
  str.length > max ? str.slice(0, max - 3) + '...' : str;
truncate('A very long string', 12)  // "A very lo..."

Count Occurrences

const count = (str, sub) => str.split(sub).length - 1;
count('hello world hello', 'hello')  // 2

Performance Tips

Conclusion

JavaScript's string methods cover virtually every text manipulation task you'll encounter. Master slice, split, replace, includes, and template literals, and you'll handle 90% of string operations with ease. The newer methods like at(), replaceAll(), and matchAll() fill important gaps. Bookmark this guide as a reference — you'll come back to it often.

🔧 Related Wootils Tools:
Case Converter · Word Counter · Text to Slug · Regex Tester