JavaScript String Methods: slice, includes, split and More
Strings hold text. You can write them with single quotes, double quotes or backticks; the first two are identical, and backticks add extra features covered in the next chapter. Strings are immutable: every method returns a new string and leaves the original unchanged.
Length and characters
word.length is the number of characters (more precisely, UTF-16 code units, so some emoji count as two). Square brackets read one character, starting at 0: word[0]. The at() method also accepts negative positions counting from the end, so word.at(-1) is the last character; it is available in all current browsers and Node.js 16.6 and later.
Extracting parts
slice(start, end) returns the characters from start up to, but not including, end. Negative numbers count from the end, so word.slice(-6) gives the last six characters. There is an older substring() method with slightly different rules for negative values; slice is the one to remember.
Expected output
10 J t Java Script JAVASCRIPT javascript true 1 true trim me| ["a", "b", "c"] hahaha 007 one 2 2
Searching
includes(text)returnstrueorfalse.indexOf(text)returns the position of the first match, or-1if there is none.startsWith()andendsWith()check the edges.
All of these are case-sensitive. To compare without case, lowercase both sides first with toLowerCase().
Transforming
toUpperCase()andtoLowerCase()change case.trim()removes whitespace at both ends;trimStart()andtrimEnd()handle one side.split(separator)returns an array of pieces, and the array methodjoin()reverses it.repeat(n)repeats the string.padStart(length, fill)andpadEnd()pad to a fixed width, handy for zero-padded numbers like007.replace(a, b)replaces the first match only, whilereplaceAll(a, b)replaces every match.
Because each method returns a string, you can chain them: input.trim().toLowerCase().
Common mistakes
- Expecting
replace("a", "b")to change every occurrence; usereplaceAll. - Testing
if (text.indexOf("x")). A match at position 0 is falsy and-1is truthy. Useincludes(). - Calling a method and forgetting to store the result.
Summary
- Strings are immutable; methods return new strings.
slice()extracts,includes()andindexOf()search,split()breaks into an array.replacechanges the first match;replaceAllchanges all of them.
Quiz: Strings