String
string · String
Text in JavaScript is a string: an immutable sequence of UTF-16 code units. The lowercase string is the primitive you use every day; the capitalized Stringis its wrapper object and the home of the static helpers. Everything below — every method, every overload — lives on String.prototype.
Usage
Three ways to hold text. Reach for the first two; the third is a historical footgun kept for compatibility.
const name = "ada"; // literal — this one, always
const hi = "hello, " + name; // or a template literal — interpolation + multiline
const boxed = new String("ada"); // avoid — an object, not a primitive
typeof name; // "string"
typeof boxed; // "object" — === against literals failsHow it works
A string is a primitive, yet you call methods on it. When you write "ada".toUpperCase(), the engine briefly wraps the primitive in a String object, runs the prototype method, and discards the wrapper. You never see the box.
Strings are immutable. No method edits in place; each returns a new string. Chaining like s.trim().toLowerCase() is the normal style, and each step allocates.
Underneath, text is UTF-16: length, indexing, charAt, and slice count 16-bit code units. Most characters fit in one unit, but emoji and some scripts need two (a surrogate pair), so "🦀".length === 2. For real characters, use the astral-aware tools: codePointAt, at, and the [Symbol.iterator], which yields whole code points.
Instance API
Everything on String.prototype, grouped by job. Signatures are the TypeScript 7.0 standard library types.
- includes(searchString: string, position?: number): boolean
- Whether the string contains the search. #
- startsWith(searchString: string, position?: number): boolean
- Whether the string opens with the search. #
- endsWith(searchString: string, endPosition?: number): boolean
- Whether the string closes with the search. #
- slice(start?: number, end?: number): string
- Section between indices. Negatives count back from the end. #
- substring(start: number, end?: number): string
- Like slice, but clamps negatives to 0 and swaps when start > end. #
- split(separator: string | RegExp, limit?: number): string[]
- Divides the string around each separator. #
- toLocaleLowerCase(locales?: Intl.LocalesArgument): string
- Lowercases following locale rules, e.g. Turkish dotted I. #
- replace(searchValue: string | RegExp, replaceValue: string): string
- Replaces the first occurrence. #
- replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string
- Replaces each match with the callback's return. #
- replaceAll(searchValue: string | RegExp, replaceValue: string): string
- Replaces every occurrence. A regex must use the /g flag. #
- matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>
- Iterator over every match with captures. The regex must use /g. #
Static API
Called on String itself. For building strings from codes rather than transforming them.