String Methods
The everyday methods for searching, slicing, and transforming text — every one returns a new string, since strings are immutable.
str.trim() / str.slice(start, end) / str.includes(sub) / str.replace(a, b) / str.split(sep)
Purpose
String.prototype provides methods for searching, extracting, and transforming text. None of them
mutate the string they’re called on — strings are primitives, and primitives can’t be mutated —
every method returns a new string (or a different type, like an array or boolean).
Common methods
' Hello, World! '.trim(); // "Hello, World!"
'hello'.slice(1, 3); // "el"
'Hello'.toLowerCase(); // "hello"
'Hello, World'.includes('World'); // true
'Hello, World'.replace('World', 'JS'); // "Hello, JS"
'a,b,c'.split(','); // ["a", "b", "c"]
'5'.padStart(2, '0'); // "05"
'hello'.at(-1); // "o" — negative index from the end
Behavior notes
slice(start, end)accepts negative indexes, counting from the end of the string.replace(a, b)only replaces the first match unless the first argument is a regular expression with the global flag (/pattern/g).split()with no argument returns an array containing the whole string as one element;split('')splits into individual characters (though this can split multi-code-point characters incorrectly — see the Unicode note below).- Comparison and length behave per UTF-16 code unit, not per visible character — some emoji and
accented characters occupy more than one code unit, so
.lengthcan report a larger number than the visible character count suggests.
Common mistakes
- Calling a string method and expecting it to mutate the original (
str.trim(); console.log(str);) — the return value must be captured (str = str.trim();) or used directly. - Assuming
.lengthalways equals the number of “characters” a person would count — true for plain ASCII text, not guaranteed for all Unicode text.
Runtime notes
Standard String.prototype methods, identical across every current browser and Node version.