Advanced20 min read

String Methods

Explore JavaScript string methods for searching, extracting, transforming, and manipulating text data.

String Basics

Strings in JavaScript are immutable — once created, a string value cannot be changed. Any method that appears to modify a string actually returns a brand new string.

You can create strings using single quotes, double quotes, or backticks (template literals):

javascript
const single = 'Hello';
const double = "Hello";
const template = `Hello, ${name}!`; // template literal with interpolation

Every string has a length property:

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

You can access individual characters using bracket notation or the charAt() method:

javascript
const word = 'JavaScript';
console.log(word[0]);        // 'J'
console.log(word.charAt(4)); // 'S'
console.log(word[word.length - 1]); // 't' (last character)

Strings are also iterable, which means you can loop over them with a for...of loop:

javascript
for (const char of 'Hello') {
  console.log(char); // 'H', 'e', 'l', 'l', 'o'
}

Searching Strings

JavaScript provides several methods for finding content within a string.

indexOf(substring) returns the index of the first occurrence, or -1 if not found:

javascript
const text = 'Hello, World!';
console.log(text.indexOf('World')); // 7
console.log(text.indexOf('xyz'));   // -1

lastIndexOf(substring) works the same but searches from the end:

javascript
const path = 'folder/subfolder/file.txt';
console.log(path.lastIndexOf('/')); // 16

includes(substring) returns a boolean — simpler when you only need to know if the substring exists:

javascript
console.log('JavaScript'.includes('Script')); // true
console.log('JavaScript'.includes('script')); // false (case-sensitive)

startsWith() and endsWith() check the beginning or end of a string:

javascript
const filename = 'report.pdf';
console.log(filename.startsWith('report')); // true
console.log(filename.endsWith('.pdf'));      // true

search(regex) works like indexOf but accepts a regular expression:

javascript
const text = 'Hello World 123';
console.log(text.search(/\d+/)); // 12 (index where digits start)

Extracting & Transforming

Extracting substrings:

slice(start, end) extracts a section of a string. The end index is exclusive. Negative indices count from the end:

javascript
const str = 'JavaScript';
console.log(str.slice(0, 4));  // 'Java'
console.log(str.slice(4));     // 'Script'
console.log(str.slice(-6));    // 'Script'

substring(start, end) is similar to slice but does not support negative indices.

Changing case:

javascript
console.log('hello'.toUpperCase()); // 'HELLO'
console.log('HELLO'.toLowerCase()); // 'hello'

Removing whitespace:

javascript
const padded = '  Hello  ';
console.log(padded.trim());      // 'Hello'
console.log(padded.trimStart()); // 'Hello  '
console.log(padded.trimEnd());   // '  Hello'

Padding strings:

javascript
console.log('5'.padStart(3, '0'));  // '005'
console.log('Hi'.padEnd(10, '.')); // 'Hi........'

Repeating:

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

Splitting & Joining

split(separator) divides a string into an array of substrings:

javascript
const csv = 'apple,banana,cherry';
const fruits = csv.split(',');
console.log(fruits); // ['apple', 'banana', 'cherry']

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

Array.join(separator) is the reverse — it combines array elements into a string:

javascript
const parts = ['2024', '01', '15'];
console.log(parts.join('-')); // '2024-01-15'

replace(search, replacement) replaces the first occurrence:

javascript
const text = 'Hello World World';
console.log(text.replace('World', 'JS')); // 'Hello JS World'

replaceAll(search, replacement) replaces all occurrences:

javascript
console.log(text.replaceAll('World', 'JS')); // 'Hello JS JS'

These methods are frequently chained together for powerful text transformations:

javascript
const input = '  hello, world!  ';
const result = input.trim().toUpperCase().replace('WORLD', 'JS');
console.log(result); // 'HELLO, JS!'

String Methods in Action

html
<div id="output"></div>

<script>
  const original = "  JavaScript is Awesome!  ";

  // Trimming and transforming
  const trimmed = original.trim();
  const upper = trimmed.toUpperCase();
  const replaced = upper.replace('AWESOME', 'POWERFUL');

  // Searching
  const hasJS = trimmed.includes('JavaScript');
  const position = trimmed.indexOf('is');

  // Splitting and joining
  const words = trimmed.split(' ');
  const reversed = words.reverse().join(' ');

  const output = document.getElementById('output');
  output.innerHTML = `
    <p>Original: "${original}"</p>
    <p>Trimmed: "${trimmed}"</p>
    <p>Uppercase: "${upper}"</p>
    <p>Replaced: "${replaced}"</p>
    <p>Includes "JavaScript": ${hasJS}</p>
    <p>Index of "is": ${position}</p>
    <p>Words reversed: "${reversed}"</p>
  `;
</script>

What does 'hello'.indexOf('z') return?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.