Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript String Methods

JavaScript strings are at the heart of UI labels, form inputs, file paths, JSON, and network data. The moment you start building anything real, you need to find text, extract parts, clean whitespace, standardize casing, and safely validate user input. String methods are the toolbox that makes that work reliable and readable.

Because strings are immutable, every method returns a new value instead of modifying the original. This makes string operations safer, but it also means you should store the result when you want the change. Knowing which methods to reach for keeps your code compact: use includes and startsWith for checks, slice and substring for extraction, split for parsing, replace/replaceAll for transformations, and trim for cleanup. When you work with emoji or accents, codePointAt and normalize help you avoid subtle Unicode bugs.

This guide covers all commonly used instance methods and the core static helpers on String, with short explanations and examples. Use it as a practical reference while you code and as a reminder of the tradeoffs between similar methods like slice vs substring or replace vs replaceAll.

Why We Need It

Nearly every app handles text, from names and emails to UI labels.

Knowing string methods makes this work easy and reliable.

Syntax

str.slice(start, end)
str.split(delimiter)
str.replace(search, value)
str.includes(text)

Basic Example

1. Character access (at, charAt)

const word = "JavaScript";
console.log(word.at(0)); // J
console.log(word.at(-1)); // t
console.log(word.charAt(4)); // S

Read characters by index. at() supports negative indexing.

Real World Example

2. Unicode inspection (charCodeAt, codePointAt)

const letter = "A";
console.log(letter.charCodeAt(0)); // 65

const emoji = "💖";
console.log(emoji.codePointAt(0)); // 128150

Use charCodeAt for UTF-16 units and codePointAt for full Unicode code points.

Multiple Use Cases

Access & Inspect

Use these methods to read characters or compare strings without changing them.

They are ideal for parsing, validation, and quick checks.

  • at(index): read a character (supports negative indexes). Example: `'JavaScript'.at(-1) // 't'`
  • charAt(index): character at a position. Example: `'code'.charAt(1) // 'o'`
  • charCodeAt(index): UTF-16 code unit. Example: `'A'.charCodeAt(0) // 65`
  • codePointAt(index): full Unicode code point. Example: `'💖'.codePointAt(0) // 128150`
  • localeCompare(other): compare for sorting. Example: `'a'.localeCompare('b') // -1`
  • toString() / valueOf(): return string value (rarely needed, but available).

Search & Match

Find text with simple queries or regular expressions.

Use these methods for filters, validations, and quick lookups.

  • includes(text): true/false containment. Example: `'hello'.includes('ell') // true`
  • startsWith(text) / endsWith(text): prefix/suffix checks. Example: `'file.txt'.endsWith('.txt')`
  • indexOf(text) / lastIndexOf(text): position of text. Example: `'a-b-a'.lastIndexOf('a') // 4`
  • search(regex): index of regex match. Example: `'abc123'.search(/\d+/) // 3`
  • match(regex): returns match array. Example: `'2024'.match(/\d+/) // ['2024']`
  • matchAll(regex): iterator of all matches. Example: `Array.from('a1b2'.matchAll(/\d/g))`

Extract & Split

Extract parts of a string or split it into pieces.

These are common when parsing input, URLs, or CSV data.

  • slice(start, end): substring with negatives allowed. Example: `'abcdef'.slice(1, 4) // 'bcd'`
  • substring(start, end): like slice but swaps arguments and no negatives.
  • split(delimiter): array of parts. Example: `'a,b,c'.split(',') // ['a','b','c']`

Modify & Format

Transform text to new strings. Remember strings are immutable.

Use these to clean input, format UI labels, or normalize data.

  • concat(...parts): combine strings. Example: `'Hello'.concat(' ', 'JS')`
  • repeat(count): repeat a string. Example: `'ha'.repeat(3) // 'hahaha'`
  • replace(search, value): replace first match. Example: `'a-a'.replace('-', ':') // 'a:a'`
  • replaceAll(search, value): replace every match. Example: `'a-a'.replaceAll('-', ':')`
  • padStart(len, fill) / padEnd(len, fill): pad to length. Example: `'7'.padStart(3, '0') // '007'`
  • trim() / trimStart() / trimEnd(): remove surrounding whitespace.
  • toLowerCase() / toUpperCase(): basic casing.
  • toLocaleLowerCase() / toLocaleUpperCase(): locale-aware casing.

Unicode & Normalization

When working with accented characters or emoji, Unicode matters.

Normalization ensures visually identical characters compare correctly.

  • normalize(form): normalize Unicode. Example: `'e\u0301'.normalize('NFC')`

Static Helpers (String)

These are called on the String object, not on instances.

They are useful for creating strings from numbers or templates.

  • String.fromCharCode(...codes): UTF-16 codes to string. Example: `String.fromCharCode(72, 73) // 'HI'`
  • String.fromCodePoint(...points): Unicode code points. Example: `String.fromCodePoint(0x1f4a9) // '💩'`
  • String.raw`...`: raw template string (keeps backslashes). Example: String.raw`C:\new`

More Examples

3. Search basics (includes, startsWith, endsWith)

const file = "report.final.pdf";
console.log(file.includes("final")); // true
console.log(file.startsWith("report")); // true
console.log(file.endsWith(".pdf")); // true

Fast checks for containment and prefixes/suffixes.

4. Finding positions (indexOf, lastIndexOf, search)

const text = "a-b-a-c";
console.log(text.indexOf("a")); // 0
console.log(text.lastIndexOf("a")); // 4
console.log(text.search(/c/)); // 6

Use indexOf/lastIndexOf for string search and search for regex.

5. Regex matches (match, matchAll)

const input = "A1 B22 C333";
console.log(input.match(/\d+/g)); // ['1','22','333']

const all = Array.from(input.matchAll(/(\w)(\d+)/g));
console.log(all.map((m) => m[0]));

match returns arrays; matchAll gives an iterator for all matches with groups.

6. Extracting substrings (slice, substring)

const word = "javascript";
console.log(word.slice(0, 4)); // java
console.log(word.slice(-6)); // script
console.log(word.substring(4, 10)); // script

slice supports negative indexes; substring does not.

7. Split strings into arrays

const csv = "red,green,blue";
const parts = csv.split(",");
console.log(parts); // ['red','green','blue']

split is perfect for CSV or path parsing.

8. Replace and replaceAll

const msg = "2024-03-15";
console.log(msg.replace("-", "/")); // 2024/03-15
console.log(msg.replaceAll("-", "/")); // 2024/03/15

replace only changes the first match; replaceAll changes all.

9. Padding and repeating

const id = "7";
console.log(id.padStart(4, "0")); // 0007
console.log(id.padEnd(4, "0")); // 7000
console.log("ha".repeat(3)); // hahaha

padStart/padEnd format IDs or columns; repeat is good for UI effects.

10. Trimming whitespace

const raw = "  hello  ";
console.log(raw.trim()); // "hello"
console.log(raw.trimStart()); // "hello  "
console.log(raw.trimEnd()); // "  hello"

Trim user input before validation or storage.

11. Case conversion

const name = "İstanbul";
console.log(name.toUpperCase());
console.log(name.toLocaleUpperCase("tr-TR"));

Locale-aware methods handle special casing rules.

12. Normalization and comparison

const a = "e\u0301";
const b = "é";
console.log(a === b); // false
console.log(a.normalize("NFC") === b.normalize("NFC")); // true
console.log("b".localeCompare("a")); // 1

Normalize for safe comparisons; localeCompare helps with sorting.

13. Static helpers (String)

console.log(String.fromCharCode(72, 73)); // HI
console.log(String.fromCodePoint(0x1f60a)); // 😊
console.log(String.raw`C:\new`); // C:\new

Use static helpers to build strings from codes or raw templates.

Comparison

Without

let out = "";
for (const ch of str) {
  if (ch !== "-") out += ch;
}

With

const out = str.replaceAll("-", "");

Common Mistakes and Fixes

Expecting mutation

String methods return new strings; originals stay unchanged.

Using indexOf for booleans

Use includes when you only need true or false.

Forgetting regex for replaceAll

Use replaceAll or a global regex for multiple matches.

Interview Questions

Do string methods mutate?

No, they return new strings.

includes vs indexOf?

includes returns a boolean; indexOf returns a position.

How do you trim whitespace?

Use trim, trimStart, or trimEnd.

Practice Problem

Practice: Remove all spaces from a string and convert it to lowercase.

const text = "Hello World";
// TODO: clean text

One Possible Solution

const text = "Hello World";
const cleaned = text.replaceAll(" ", "").toLowerCase();
console.log(cleaned);

Frequently Asked Questions

Are strings mutable?

No, strings are immutable in JavaScript.

How do I check if a string contains text?

Use includes or indexOf.

How do I split a string?

Use split with a delimiter.

When should I use locale-aware casing?

Use toLocaleLowerCase/UpperCase for user-facing text in specific locales.

Try It Yourself

Try different slice and split values.