10 Must Know JavaScript string methods

10 Must Know JavaScript string methods
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2019. If you want find a great place for interactive tutorials, i recommend Educative ( Disclaimer: the link it's affiliate ) where I'm currently finishing to build my JavaScript course.

string is a JavaScript's primitive type that is used to represent a sequence of characters. They are used to store much different information, from names, product descriptions, etc.. and hopefully NOT passwords!.

In this article, we are going to look at 10 String methods that you will see yourself use on an almost daily basis once you start working with JavaScript.

At the end of this article you will find a link to download a set of flashcards to bring with you and revise the concepts discussed in this article.

If you are not too familiar with JavaScript you may be wondering why string (the primitive) and String. in the method names are written in two different cases. The answer is that lowercase string refers to the primitive type while uppercase String refers to the global object on which we can call several built-in methods.

The conversion between the primitive string and the String object is done automatically and that is why you don't have to write code like the following:

const primitiveString = 'Alberto';

const str = new String([primitiveString]);
str.length; // 7

Here we are creating a new String object from our original string but since JavaScript does the conversion automatically we can simply call the String methods directly on the primitive like this:

const primitiveString = 'Alberto';
primitiveString.length; // 7

Now that we covered some basics, let's start looking at some useful methods.


String.prototype.indexOf()

The String.prototype.indexOf() returns the index of the first occurrence in the calling String object of the value that we specify as an argument.

const str = "Watermelon";
str.indexOf("melon"); // 5
const str2 = "My dog is named boo. My dog is 7 years old";
str2.indexOf('dog'); // 3
const str3 = "My DOG is named boo. My dog is 7 years old";
str3.indexOf('dog'); // 24

In the second String, the word "dog" appears twice but indexOf() only returns the index of the first occurrence.

In the third String you will see that "DOG" is now uppercase, thus the result changed from '3' to '24' because the indexOf() method is case sensitive.


String.protoype.includes()

The String.protoype.includes() method is similar to the previous, in that it's used to find one string inside another one but it won't return the index of it but simply a boolean, whether the first string can or cannot be found in the second one.

const str = "Watermelon";
str.includes("melon"); // true
const str2 = "WATERMELON";
str2.includes("melon"); // false

As you can see, this method is also case sensitive, returning us false where looking for lowercase "melon" inside of uppercase "WATERMELON".

Since these two methods are very similar, you may be wondering why you should use one over the other and the answer is simply to choose the one that best fits what you are trying to achieve.

Do you need to know at what index does string B appear in string A? use indexOf(). Conversely, are you just checking if string B is present in string A? You could use something like: a.indexOf(b) !== -1 but you should just use includes() for better clarity of your code.


String.protoype.startsWith() / String.protoype.endsWith()

These two methods have been added with the ECMAScript 2015 (ES6) specification and are used to determine if one string starts, or ends, with a specified set of characters returning true of false appropriately.

Similar to the two methods above, these two are also case sensitive

Both methods can take two parameters, the first one is the same for both and it's a string. The second one differs between the two methods:

  • startsWith() can take an optional parameter indicating the starting position where to begin searching for a string. It defaults to 0
  • endsWith() can take an optional parameter indicating the length of the original string to check. It defaults to the length of the string.

Let's look at the following examples for startsWith()

const str = "Watermelon";
str.startsWith('Water'); // true
str.startsWith('Water', 1); // false
str.startsWith('melon',5 ) // true
str.startsWith('lon',7 ) // false

Let's break the code down:

  • str.startsWith('Water'); returns true because "Watermelon" includes the string 'Water' right at the beginnng
  • str.startsWith('Water', 1); returns false because the string that is used as the base to check is the original string starting at index 1 which equals to 'atermelon'
  • str.startsWith('melon',5 ) and str.startsWith('lon',7 ) both return true because the string we used to check are the original string starting from index 5 and index 7, which equal to 'melon' and 'lon'.

Now let's look at some examples for endsWith():

const str = "Watermelon";

str.endsWith('melon'); // true
str.endsWith('me', 7) // true
str.endsWith('melon', 8) // false

Let's break the code down:

  • str.endsWith('melon') returns true because 'Watermelon' ends with 'melon'
  • str.endsWith('me', 7) returns true because we are only checking the first 7 characters of the string, which in turn transforms it from 'Watermelon' to 'Waterme'.
  • str.endsWith('melon', 8) returns false because we specified a max length of 8 which transformed the string to check to 'Watermel' which does not end with 'melon'.

String.protoype.slice()

String.protoype.slice() is a useful method to extract a section of a string into another string without modifying the original one.

This method takes two parameters: a beginning index and an end index. The second one is optional and it defaults to the end of the string if not specified.

Let's look at an example:

const str = "Watermelon";

const str2 = str.slice(1);
// atermelon
const str3 = str.slice(1,5);
// ater
const str4 = str.slice(5);
// melon
const str5 = str.slice(10);
// ''

Let's look at what we just did:

  • str.slice(1) extracts every character from index 1 to the end of the string
  • str.slice(1,5) extracts characters from index 1 to index 5
  • str.slice(5) extracts characters from index 5 to the end of the string
  • str.slice(11) extracts characters from index 11 to the end of the string. Since the string does not have 11 characters, the result we got was an empty string

educative banner

String.prototype.substring()

String.prototype.substring() is very similar to the previous slice() method, in that it is used to extract a portion of a string.

It takes two arguments, one for a start index and one for an end index.

Let's look at some examples:

const str = "Watermelon";

const str2 = str.substring(1);
// atermelon
const str3 = str.substring(1,5);
// ater
const str4 = str.substring(5);
// melon
const str5 = str.substring(10);
// ''

If you look at the examples above and compare them with the ones from the slice() method you will wonder what's the difference as they both returned the same substring.

While for the most part, you can use them interchangeably, there are differences between the two.

Look at this example for the first difference:

const str = "Watermelon";

const subStr = str.substring(10,0);
// Watermelon
const sliceStr = str.slice(10,0);
// ''

In this case, the start index was higher than the end index I've provided and as you can see the two methods behaved differently:

substring() will swap start and end index if start is higher than end while slice(), on the other hand, won't do that, thus returning an empty string.

Another difference we can observe has to do with negative indexes:

const str = "Watermelon";

const subStr = str.substring(-3);
// Watermelon
const sliceStr = str.slice(-3);
// lon

When we set the starting point as a negative value, substring() will simply treat it as 0 (and that is also valid for NaN values) while slice() will start counting the index from the end of a string.

That is why str.slice(-3) returned 'lon', because it started counting from 3 steps from the end of the string, all the way to the end.

For the most part, you will be fine using either slice or substring() but it is useful to know that there are some differences between the two.


String.prototype.split()

String.prototype.split() is another very useful method that turns a String into an array of strings. The string gets split based on a specified separator.

This method takes two arguments, a separator, and a limit. The separator specifies how to split the string while the limit is a non-negative integer that specifies how many split to perform.

Let's look at an example to see this method in action:

const str = "apple, banana, mango, watermelon";
const arr = str.split(', ');
// ["apple", "banana", "mango", "watermelon"]
const arr2 = str.split(', ',1);
// "apple"]

As you can see, in the first example we split our string based on this separator ', ' which means that every string in between a comma followed by a space got put into the array.

In the second example, I also passed a limit of 1 which told the method to perform only one split, thus returning an array with only one element inside.


String.prototype.trim() / String.prototype.trimEnd() / String.prototype.trimStart()

String.prototype.trim() removes whitespaces from both the end and the beginning of a string. String.prototype.trimEnd() removes them only from the end while String.prototype.trimStart() removes them only from the start.

These are pretty straightforward, but let's look at an example:

const str = " watermelon ";

const trim = str.trim();
// "watermelon"
const trimStart = str.trimStart();
// "watermelon "
const trimEnd = str.trimEnd();
// " watermelon"

String.prototype.padStart() / String.prototype.padEnd()

These two methods may seem like the opposite of the trim() method but while they can be used to add whitespace to the beginning or end of a string, they can do more than that.

They take two arguments, one for the length of the retuning string after the pad has been added (if lower than the current length of the string, the string is returned as-is, without any modification) and another argument for the string to add at the beginning or end of the original one. If it's long to fit in the length we defined in the first argument, it will be truncated.

Let's look at a few examples:

const str = "Watermelon";

const str2 = str.padStart(15, " ");
// " Watermelon"
const str3 = str.padEnd(15, " ");
// "Watermelon "

In the examples above we used padStart() and padEnd() to add whitespace to the string. Since we defined our max length as 15, and the length of the original string was 10, 5 characters were added to the string as whitespace (" ").

As mentioned above, we are not limited to add whitespace, we can also add new strings onto the original one.

const str = "Watermelon";

const str2 = str.padStart(17, "I like ");
// "I like Watermelon"
const str3 = str.padStart(11, "I like ");
// "I Watermelon"
const str4 = str.padEnd(19, " is yummy");
// "Watermelon is yummy"
const str5 = str.padEnd(13, " is yummy");
// "Watermelon is"

As you can see, we managed to add a new string onto the original one but when the string to add was too long for our specified length, it got truncated, resulting in "I Watermelon" and "Watermelon is".


String.prototype.toUpperCase() / String.prototype.toLowerCase()

There's not much to say about these two methods as they are very straightforward in what they do. String.prototype.toUpperCase() transforms a string in uppercase whilst String.prototype.toLowerCase() transforms it into lowercase. Both are useful when you want to display a string differently from how it's stored in your variable.

const str = "Watermelon";

str.toUpperCase();
// WATERMELON
str.toLowerCase();
// watermelon

String.prototype.concat()

String.prototype.concat() is a useful method used to concatenate a string with the calling arguments, returning a new string.

Let's look at an example:

const str = "Watermelon";
const newStr = str.concat(' is a ', 'fruit');
// Watermelon is a fruit

As you can see we called concat() on our original string and concatenated two new strings to it, returning a new string newStr. You can pass as many strings as you want as the argument of concat()


Download your set of flashcards and cheatsheet



You can find more flashcards at this link and more cheatsheets at this link



Thank you very much for reading. Follow me on DevTo or on Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Amazon and Leanpub
Disclaimer: this website opts in affiliate programs for certain products


NEWEST ARTICLES




ABOUT ME

author alberto montalesi profile picture

Alberto is a software developer specialized in building enterpise software using Angular and author of the 'Complete guide to Modern JavaScript' ebook and course. In his free time he writes articles and tutorials on InspiredWebDev.com and Dev.to

You can read more about him here