DEV Community

Cover image for 10 Must know JavaScript string methods for everybody
AlbertoM
AlbertoM

Posted on • Updated on • Originally published at inspiredwebdev.com

10 Must know JavaScript string methods for everybody

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials.

Hi, I am Alberto Montalesi, a full-stack self-taught developer. I create practical JavaScript tutorials and courses on my website inspiredwebdev.com to inspire other developers to grow and build the career that they want.

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

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.

Keep reading...


Thank you very much for reading. Follow me on DevTo or on my blog at inspiredwebdev or on twitter. Check out Educative.io for interactive programming courses.

Disclaimer: Links to Amazon and Educative are affiliate links, purchases you make will generate extra commissions for me. Thank you


book banner

Get my ebook on Amazon and Leanpub

Top comments (2)

Collapse
 
paulstr profile image
paulStr

Thanks for the post, nice to read and easy to understand examples.

There`s a small issue with the code breakdown of endsWith,
str.endsWith('melon', 8) returns true should return false.

Collapse
 
albertomontalesi profile image
AlbertoM

You are right! I've fixed it now