DEV Community

Cover image for 🚀 26 Built-in String Methods | JavaScript
Niall Maher
Niall Maher

Posted on

🚀 26 Built-in String Methods | JavaScript

You can watch the video version here or keep scrolling for the code snippets.

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

🔗 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 ""
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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ú"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

matchAll

A new feature in ES2020 so check your browser compatibility. matchAll is like the match method on steroids. It returns an 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 ] */

Enter fullscreen mode Exit fullscreen mode

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ú"
Enter fullscreen mode Exit fullscreen mode

 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*****"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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".
Enter fullscreen mode Exit fullscreen mode

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 occurance.

"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"
Enter fullscreen mode Exit fullscreen mode

 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 global regexs 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"
Enter fullscreen mode Exit fullscreen mode

 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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"] 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

 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" 
Enter fullscreen mode Exit fullscreen mode

toLowerCase

Converts a string to lowercase letters

"HeLlO wOrLd".toLowerCase(); // returns "hello world"
Enter fullscreen mode Exit fullscreen mode

toUpperCase 

Converts a string to uppercase letters.

"Hello world".toUpperCase(); // returns "HELLO WORLD"
Enter fullscreen mode Exit fullscreen mode

trim 

Removes whitespace from both ends of a string.

"   Hello world   ".trim(); // returns "Hello world"
Enter fullscreen mode Exit fullscreen mode

trimEnd

Trims whitespace from the end

"   Hello world   ".trim(); // returns "   Hello world"
Enter fullscreen mode Exit fullscreen mode

trimStart

Trims whitespace from the start of a string.

"   Hello world   ".trim(); // returns "Hello world   "
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Subscribe on Codú Community

Top comments (8)

Collapse
 
aminnairi profile image
Amin

Hi there,

I have some little experience in JavaScript now and just discovered the matchAll method thanks to you. It's always great to read these kind of articles on DEV to catch up without having to open N tabs for each languages we know everyday.

Very concise, with little examples. Perfect for people like me. Keep going these kind of articles.

See you for ES2021!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Shortcut for charAt:

"Hello world!"[7]    // returns 'o'

Slight difference with an out of range index though - it will return undefined

Collapse
 
nialljoemaher profile image
Niall Maher

Thanks! I'll update it. 💜
Must be the REPL I ran it in because I ran all the code too and pasted the outputs.

Collapse
 
nialljoemaher profile image
Niall Maher • Edited

I misread it when I was out I now see what you're saying. 🤦‍♂️ Nice trick! 💜

Collapse
 
venoel profile image
venoel

Is this article for developers who do not know how to read manuals and documentation?

Collapse
 
nialljoemaher profile image
Niall Maher

A lot of people, especially new can get a little overwhelmed with the docs (I know I got a little overwhelmed) so it's more of an overview that's not so detailed so that people can be aware of tools that are available.

Collapse
 
muhimen123 profile image
Muhimen

Sometimes, documentation is never enough(or can be confusing).

Collapse
 
dansimiyu profile image
dan-simiyu

Good read