🚀 26 Built-in String Methods | JavaScript

🚀 26 Built-in String Methods | JavaScript

Featured on daily.dev

In this article, we will take a look at 26 different built-in string methods in JavaScript. There is no need to memorise all of the built-in methods available to us in JavaScript, but by being aware of what ones are available, you will save yourself reinventing them when the time comes that you need one of these.

⏰ There are links in the video description for all the timestamps so you can jump to the parts you like. 💜

🔗 Note: All the titles are links to the MDN docs.

charAt

Returns the character at the specified index.

"Hello World".charAt(2); // returns "l"
// If we pass no value it defaults to an index of 0
"Hello World".charAt(); // returns "H"
// If we add an index that is undefined we get an empty string
"Hello World".charAt(20); // returns ""

charCodeAt

Returns the unicode of the character at the specified index.

"Hello world".charCodeAt(2); // returns 72 for "l"
// If we pass no value it defaults to an index of 0
"Hello world".charCodeAt(); // returns 108 for "H"

concat

Joins two or more strings, and returns a single concatenated string. It's very similar to using the + operator on strings.

"Hello".concat(" world"); // returns "Hello world"
// With multiple strings
"Hello".concat(" world", " and", " other", " planets"); // returns "Hello world and other planets"

endsWith

Checks whether a string ends with specified string. We can add an optional second parameter with a limit to the string.

"Dogs are the best!".endsWith('best'); // returns false
"Dogs are the best!".endsWith('best!'); // returns true
// With second parameter for ending index
"Dogs are the best!".endsWith('best', 17); // returns true (because we picked the end of the string is at index 17)

fromCharCode

Converts Unicode values to readable characters. fromCharCode is one of the few static methods available on the String Object. All the other ones we have been using have been what is known as an instance property. We access it by using the String keyword.

String.fromCharCode(67); // returns "C"
// Using multiple characters
String.fromCharCode(67, 111, 100, 250); // returns "Codú"

includes

Checks whether a string contains a specific string.

"Dogs are the best!".includes("Dogs") // returns true
// With optional starting index
"Dogs are the best!".includes("Dogs", 1) // returns false
"Dogs are the best!".includes("ogs", 1) // returns true

indexOf

Returns the position of the first found occurrence of a specified value in a string.

"test one two test".indexOf("test") // returns 0
"test one two test".indexOf("x") // returns -1
// With optional starting index
"test one two test".indexOf("test", 1) // returns 13

lastIndexOf

Returns the position of the last found occurrence of a specified value in a string.

"test one two test".lastIndexOf("test") // returns 13
// With optional limit because search starts from index 12.
"test one two test".lastIndexOf("test", 12) // returns  0

match

The match() method retrieves the result of matching a string against a regular expression or string.

// returns the first match
"This is the BEST".match("i"); // returns a regex iterator like this ["i", index: 2, input: "This is the BEST", groups: undefined]
// With a regex looking for uppercase characters
"This is the BEST".match(/[A-Z]/); // returns a regex iterator like this ["T", index: 0, input: "This is the BEST", groups: undefined]
// you can get all the matches without the details if you use a global regular expression
"This is the BEST".match(/[A-Z]/g); // returns [ 'T', 'B', 'E', 'S', 'T' ]

matchAll

A new feature in ES2020 so check your browser compatibility. matchAll is like the match method on steroids. It returns a RegExpStringIterator for the matches.

// Working with with the RegExpStringIterator can become easy to work with if we spread it into an array.
const matches = [..."This is the BEST".matchAll(/[A-Z]/g)];
matches.forEach(element => console.log(element)); 

/* 
console.logs 
[ 'T', index: 0, input: 'This is the BEST', groups: undefined ]
[ 'B', index: 12, input: 'This is the BEST', groups: undefined ]
[ 'E', index: 13, input: 'This is the BEST', groups: undefined ]
[ 'S', index: 14, input: 'This is the BEST', groups: undefined ]
[ 'T', index: 15, input: 'This is the BEST', groups: undefined ] */

For more information on working with the iterators check out the docs.

normalize

We can normalize a unicode string with normalize, what does that mean? Basically that we can see it in human-readable form.

"\u0043\u006f\u0064\u00fa".normalize(); // returns "Codú"

padEnd

We can add "padding" to the end of a string so it equals a certain length. We pad it with whitespace by default but can choose replacement characters too.

// Entire length is 10 after padding
"Hello".padEnd(10); // returns "Hello     "
// Entire length is 10 after padding with characters too
"Hello".padEnd(10, "*"); // returns "Hello*****"

padStart

We can add "padding" to the start of a string so it equals a certain length. We pad it with whitespace by default but can choose replacement characters too.

// Entire length is 10 after padding
"Hello".padStart(10); // returns "     Hello"
// Entire length is 10 after padding with characters too
"Hello".padStart(10, "*"); // returns "*****Hello"

These padding might seem irrelevant but there was a case where a popular library that was pulled from npm that did this was pulled and basically broke the internet. You can google the left-pad incident for information on that.

repeat

Takes a number as an argument and repeats the string as many times as specified and returns as a single string.

"Hello".repeat(3); // returns "HelloHelloHello".

replace

Searches a string for a specified value, or a regular expression, and returns a new string where the specified value(s) are replaced. We can replace these values with a string or pass a function to operate on the match. Unless we pass a global regex it will only replace the first found occurrence.

"cat, cat, cat".replace(/cat/, 'dog'); // returns "dog, cat, cat"
"cat, cat, cat".replace(/cat/g, 'dog'); // returns "dog, dog, dog"
"cat, cat, cat".replace("cat", 'dog'); // returns "dog, cat, cat"
"cat, cat, cat, bird".replace("cat", (i) => i + "dog"); // returns "catdog, cat, cat, bird"

replaceAll

We can use a regex or string to replace all instances of a string. We can replace these values with a string or pass a function to operate on the match. When working with global regex's there is not much difference between replace and replaceAll. Replace all only takes a global regex but if you pass it a string it will automatically replace all instances of that string. The second param can be a string to replace each instance or a function to operate on each instance.

"cat, cat, cat, bird".replaceAll(/cat/g, 'dog'); // returns "dog, dog, dog, bird" 
"cat, cat, cat, bird".replaceAll("cat", 'dog'); // returns "dog, dog, dog, bird" 
// With a function
"cat, cat, cat, bird".replaceAll("cat", (i) => i + "dog"); // returns "catdog, catdog, catdog, bird"

search

Searches a string for a specified value, or regular expression, and returns the starting position of the match.

"cat, dog, cat".search("dog"); // returns 5
// With a regex
"cat, dog, cat".search(/dog/g); // returns 5

slice

Extracts a part of a string and returns a new string.

"This is a string I want to slice".slice(27); // returns 'slice'
"This is a string I want to slice".slice(27, 28); // returns 's'
// And we can work backwards with negative values such as
"This is a string I want to slice".slice(-5); // returns "slice"
"This is a string I want to slice".slice(-5, -1); // returns "slic"

split

Splits a string into an array of substrings. We can give an optional limit as a second parameter.

// For all characters to be split give an empty string
"Hello darkness".split(""); // returns ["H", "e", "l", "l", "o", " ", "d", "a", "r", "k", "n", "e", "s", "s"]
// To split at spaces
"Hello darkness my old friend".split(" "); // returns ["Hello", "darkness", "my", "old", "friend"]  
To limit the return length we can use an optional second parameter
"Hello darkness my old friend".split(" ", 2); // returns ["Hello", "darkness"]

startsWith

Checks, whether a string begins with specified characters and returns a boolean. We can give it an optional starting index as a second parameter.

"Hello".startsWith("h"); // true
"Hello".startsWith("e"); // false
// With optional starting index
"Hello".startsWith("e", 1); // true

substring

Extracts the characters from a string, between two specified indices. The second parameter is optional.

"Hello".substring(1, 4); // "ell"
// If we give no second parameter it will pick assume you have no end index.
"Hello".substring(1); // returns "ello"

toLowerCase

Converts a string to lowercase letters

"HeLlO wOrLd".toLowerCase(); // returns "hello world"

toUpperCase

Converts a string to uppercase letters.

"Hello world".toUpperCase(); // returns "HELLO WORLD"

trim

Removes whitespace from both ends of a string.

"   Hello world   ".trim(); // returns "Hello world"

trimEnd

Trims whitespace from the end

"   Hello world   ".trim(); // returns "   Hello world"

trimStart

Trims whitespace from the start of a string.

"   Hello world   ".trim(); // returns "Hello world   "

Follow me on Twitter

Subscribe on Codú Community