JavaScript string methods
Table of contents
In this post, you will find useful string methods and examples on how to use them. All strings, whether they are in object form or literals, inherit from the String.prototype
object which is where all the string methods come from. This post tries to list as many useful string methods as possible, in the least possible space. It’s not meant to be an extensive reference.
Keep in mind that none of the string methods mutates the original string; they return a new string. Strings in JavaScript are immutable.
slice
str.slice(startIndex, endIndex = str.length)
Returns a portion of the string from start to end index (end not included).
String.prototype.slice()
"Hello world".slice(6); // "world"
"Hello world".slice(0, 5); // "Hello"
// for negative indices it counts from the end of the string.
"Hello world".slice(-5); // "world"
"Hello world".slice(0, -6); // "Hello"
split
str.split(splitPattern, limit = all)
Split the string into an array. The characters that match the split pattern are thrown away.
String.prototype.split()
"Hello world".split(" "); // ["Hello", "world"], words.
"Hello world".split(""); // ["H", "e", "l", "l", "o", " ", ..., "d"], characters.
"Hello world".split(); // ["Hello world"], as is.
"Hello world".split("o"); // ["Hell", " w", "rld"]
"Hello world".split(/O/i); // ["Hell", " w", "rld"], you can use regex.
"Hello world".split("", 5); // ["H", "e", "l", "l", "o"], 5 is the new array length.
indexOf
str.indexOf(searchString, fromIndex = 0)
Returns the first index if it finds the string, otherwise, it returns -1
. String.prototype.indexOf()
"imagine".indexOf("i"); // 0
"imagine".indexOf("w"); // -1, "w" doesn't exist in the string.
"imagine".indexOf("i", 1); // 4, finds the second "i".
See also String.prototype.lastIndexOf()
charAt
str.charAt(index = 0)
Returns the character at the index. String.prototype.charAt()
"learn".charAt(3); // "r"
"learn".charAt(); // "l", the first character.
"learn".charAt(99); // "", returns an empty string if the index is out of range.
includes
str.includes(string, fromIndex = 0)
See if the string contains the given string. String.prototype.includes()
"learning js".includes("js"); // true
"learning js".includes("JS"); // false, it's case-sensitive.
"learning js".includes("ea", 2); // false
match
str.match(regexp)
See if the string matches the regular expression. If you use the global flag, it returns an array with the matching strings. If you don’t use the global flag, the returned array has some additional properties. If you use both capture groups and the global flag, you won’t get back the capture groups. Array.prototype.match()
"Season 8 was bad".match(/bad/); // without the global flag, notice the extra properties.
// ["bad", index: 13, input: "Season 8 was bad", groups: undefined]
"Season 8 was bad".match(/as/g); // with global flag.
// ["as", "as"]
"Season 8 was bad".match(/\w+(as)/); // capture group, returns 1st match and the groups.
// ["Seas", "as", index: 0, input: "Season 8 was bad", groups: undefined]
"Season 8 was bad".match(/\w+(as)/g); // global and capture groups, the global wins.
// ["Seas", "was"]
"Season 8 was bad".match(/good/);
// null
"Season 8 was bad".match();
// ["", index: 0, input: "Season 8 was bad", groups: undefined]
"Season 8 was bad".match(null);
// null
See String.prototype.matchAll()
if you want to use both capture groups and the global flag. Use String.prototype.search()
if you want less details, for example, to see only if the pattern exists, and to get the index of the first match. There is also the RegExp.prototype.test()
for simple checks and the RegExp.prototype.exec()
which is similar to matchAll
.
replace
str.replace(pattern, replacementStr)
Find the regex in the string and replace it with the replacement string. The pattern can be a regex or a string.
String.prototype.replace()
"Hello there".replace(/there/, "world"); // "Hello world"
"Hello there".replace("Hello", "Hi"); // "Hi there"
"Hello there".replace("e", "3"); // "H3llo there", string pattern = replace the first.
"Hello there".replace(/e/, "3"); // "H3llo there"
"Hello there".replace(/e/g, "3"); // "H3llo th3r3"
"John Doe".replace(/(\w+)\s(\w+)/, "$2, $1"); // Doe, John, see the notice below.
See also:
- The special replacement patterns.
- Using a function instead of a replacement string.
trim
str.trim()
Removes whitespace characters from the start and from the end of the string. Whitespace characters are space, tab, line endings, etc. String.prototype.trim()
" Hello world. \n".trim(); // "Hello world."
Use trimStart
/trimLeft
to remove whitespace characters only from the beginning and trimEnd
/trimRight
to remove only from the end.
concat
str.concat(stringN)
Merge two or more strings into a new string. The +
operator is more performant.
String.prototype.concat()
"learn".concat("ing"); // "learning"
"learn".concat("ing", " ", "js"); // "learning js"
"learn".concat(1, "ng"); // "learn1ng", using numbers.
toLowerCase
str.toLowerCase()
Returns the string in lowercase. String.prototype.toLowerCase()
"Hello world".toLowerCase(); // "hello world"
See also String.prototype.toLocaleLowerCase()
toUpperCase
str.toUpperCase()
Returns the string in uppercase. String.prototype.toUpperCase()
"Hello world".toUpperCase(); // "HELLO WORLD"
See also String.prototype.toLocaleUpperCase()
startsWith
str.startsWith(searchString, fromIndex = 0)
See if the string starts with the given string. String.prototype.startsWith()
"learning js".startsWith("learn"); // true
"learning js".startsWith("js"); // false
"learning js!".startsWith("learn", 1); // false
endsWith
str.endsWith(searchString, length = str.length)
See if the string ends with the given string. String.prototype.endsWith()
"learning js".endsWith("js"); // true
"learning js".endsWith("JS"); // false, it's case-sensitive.
"learning js!".endsWith("js", 11); // true, we ignore the "!" character here.
The rest string prototype methods
padStart
padEnd
repeat
substring
, almost identical to slice.- HTML wrapper methods
Other things to read
Popular
- Reveal animations on scroll with react-spring
- Gatsby background image example
- Extremely fast loading with Gatsby and self-hosted fonts