In JavaScript, strings have a rich set of built-in methods for searching, extracting, transforming, and comparing text.
The most popular: length
, charAt
, charCodeAt
, at
, concat
, includes
, indexOf
, lastIndexOf
, startsWith
, endsWith
,
slice
, substring
, substr
, toLowerCase
, toUpperCase
, trim
, trimStart
, trimEnd
, replace
, replaceAll
, split
, repeat
.
Strings in JavaScript are immutable — this means that methods do not change the original string but return a new one.
length
Returns the number of characters in a string.
"Hello".length // 5
A common mistake is expecting that length
will return the number of bytes.
For Unicode characters (emoji
, hieroglyphs), the number of characters and bytes may differ.
charAt(index)
Returns the character at the specified index.
"JavaScript".charAt(4) // "S"
If the index is out of range, an empty string is returned.
charCodeAt(index)
Returns the numeric code of the character in UTF-16 format.
"A".charCodeAt(0) // 65
at(index)
A new method that supports negative indexes.
"Hello".at(-1) // "o"
concat(str)
Concatenates strings.
"Hello".concat(" ", "world") // "Hello world"
In practice, the +
operator or template literals are more common.
includes(substr)
Checks if a substring is contained.
"JavaScript".includes("Script") // true
Case-sensitive.
indexOf(substr)
/ lastIndexOf(substr)
indexOf
returns the first position of a substring, lastIndexOf
— the last.
"banana".indexOf("a") // 1
"banana".lastIndexOf("a") // 5
startsWith(substr)
/ endsWith(substr)
Checks the start and end of a string.
"Hello".startsWith("He") // true
"Hello".endsWith("lo") // true
slice(start, end)
Extracts a substring by indexes (supports negative indexes).
"Hello".slice(1, 4) // "ell"
substring(start, end)
Similar to slice
, but does not support negative indexes and swaps arguments if start > end
.
"Hello".substring(4, 1) // "ell"
substr(start, length)
Extracts a substring by start position and length.
"Hello".substr(1, 3) // "ell"
The method is deprecated, better use slice
.
toLowerCase()
/ toUpperCase()
Changes the case of all characters.
"JavaScript".toUpperCase() // "JAVASCRIPT"
trim()
, trimStart()
, trimEnd()
Removes whitespace from the edges of a string.
" hi ".trim() // "hi"
replace(search, value)
/ replaceAll(search, value)
replace
replaces the first match, replaceAll
— all matches.
"1-2-3".replace("-", "_") // "1_2-3"
"1-2-3".replaceAll("-", "_") // "1_2_3"
split(delimiter)
Splits a string into an array.
"apple,banana".split(",") // ["apple", "banana"]
repeat(count)
Repeats a string the specified number of times.
"ha".repeat(3) // "hahaha"
includes
, indexOf
).substr
.length
and charAt
may behave unexpectedly with emoji.💡 Tip: when searching case-insensitively, convert both strings to the same case:
"Hello".toLowerCase().includes("he") // true