When to Use these String Methods in JavaScript
Tags: algorithms, javascript, beginners, codenewbie
Published: 2021-04-23 20:11:30

There are A LOT of strings methods. This includes when you want to **find a string**, **search for a string**, **extract parts**, **replace**, **concat**, etc. There are a lot! This guide is more of a refresher and I would like to use this opportunity to categorize when we would use the following methods.

Before we move on, if you are interested in array methods and/or need a refresher on arrays, check out my friend, Waverley's [Everything JavaScript Arrays & Array Methods!](https://dev.to/wlcreate/all-about-javascript-arrays-array-methods-3n9). Give her some shoutout! 

Without further ado, here we go!

---
## Table of Contents

* [Find a String in a String](#find-a-string)
* [Extract String Parts](#extract)
* [Replace String Content](#replace)
* [All Lower Cases <=> All Upper Cases](#lower-upper)
* [Concatenation](#concatenation)
* [Remove Whitespace](#trim)
* [Methods That Exist in Both String and Array](#common-methods)
* [Conclusion](#conclusion)

---
### Find a String in a String <a name="find-a-string"></a>
`indexOf()`, `lastIndexOf()`, `charAt()` and `search()` are the go-to methods.
![Baby Dory](https://media.giphy.com/media/26BRJCP87jZmjVGko/giphy.gif)
```javascript
let findDory = "Where are Dory's parents, Dory's dad and Dory's mom?";

// indexOf() 
// returns the first index of the first occurrence of a specified text in a string 
findDory.indexOf('Dory') // 10

// lastIndexOf() 
// returns the first index of the last occurrence of a specified text in a string 
findDory.lastIndexOf('Dory') // 41

// charAt() 
// returns the character at the specified index in a string
findDory.charAt(10) // 'D'

// search()
// returns the position of the match
findDory.search('Dory') // 10
```

**Note**: You might notice how similar `search()` and `indexOf()` are. The difference is that `search()` can take regular expressions (`regexp`) as parameter and will return `-1` for unsuccessful search, while `indexOf()` can take second parameter as the starting position, but cannot take `regexp` as parameter.

What about the time when we are not interested in the index, but we just want to find if that particular substring is **included** in our string. We got another method called `includes()` (I always forgot the 's' for some reason 😅)
![Ratatouille](https://lumiere-a.akamaihd.net/v1/images/ratatouille_great-artist_d4e20b31.jpeg)
```javascript
const ratatouille = “Not everyone can become a great artist, but a great artist can come from anywhere.”

// includes()
ratatouille.includes('artist') // true
ratatouille.includes('chef') // false
```
**Note**: This is quite similar to `array`'s `find()`, `match()`, `filter()`. Check these methods out in Waverley's article!!

---
### Extract String Parts <a name="extract"></a>
`slice()` and `substring()` are the go-to methods. (Not going to cover `substr()` since it is going to be a legacy method.)
![Buzz Lightyear](https://media.giphy.com/media/5C472t1RGNuq4/giphy.gif) 
```javascript
let buzzLightyear = "To infinity and beyond!"

// slice(start[, end]) -- immutable
// extracts a section of the string and return as a new string
buzzLightyear.slice(3) // 'infinity and beyond!'
buzzLightyear.slice(3, 11) // 'infinity'

// substring(start[, end]) -- immutable
buzzLightyear.substring(3) // 'infinity and beyond!'
buzzLightyear.substring(3, 11) // 'infinity'
```
**Note 1**: `slice()` and `substring()` are very similar. However, there are some subtle differences. Here's the [breakdown](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#differences_between_substring_and_slice) from MDN.

**Note 2**: The `slice()` method works for both string and array. You might notice `splice()` is not in this category. We would use `substring()` and `substr()` as alternatives. Here's a [Stack Overflow post](https://stackoverflow.com/questions/20817618/is-there-a-splice-method-for-strings) that breaks down how to utilize the alternate `splice()` method in string.

---
### Replace String Content <a name="replace"></a>
As you can imagine, there's a built-in method called `replace()`.
```javascript
const js = "Javascript developers learn javascript because javascript is great"

// replace(searchValue, newValue) -- immutable
// returns a new string with only the first instance of the value being replaced. 
// It is also case sensitive.
js.replace("javascript", "JavaScript") 
// 'Javascript developers learn JavaScript because javascript is great'

// we can use RegExp to replace
// /g : perform global replacement to replace every match 
js.replace(/javascript/g, "JavaScript")  
// 'Javascript developers learn JavaScript because JavaScript is great'

// /gi: perform a global, case-insensitive replacement
js.replace(/javascript/gi, "JavaScript")  
// 'JavaScript developers learn JavaScript because JavaScript is great'
```
---
### All Lower Cases <=> All Upper Cases <a name="lower-upper"></a>
These two methods are two of the most commonly used methods: `toLowerCase()` and `toUpperCase()`. It's useful when you want to have all lower case characters and upper case characters respectively. 
![Frozen The Incredibles GIF](https://media.giphy.com/media/AKRBUvnTZcBLW/giphy.gif)
```javascript
const uppercase = "I AM A JAVASCRIPT DEVELOPER."

// toLowerCase() -- immutable
uppercase.toLowerCase()
// 'i am a javascript developer.'

const lowercase = 'Where is my supersuit?'
// toUpperCase() -- immutable
lowercase.toUpperCase()
// 'WHERE IS MY SUPERSUIT?'
```
---
### Concatenation <a name="concatenation"></a>
There are a few ways to concat strings: 
- the `+` operator
- template literal
- `concat()`
![Edna No Capes Gif](https://media.giphy.com/media/dePaPOPNSLDsk/giphy.gif)
```javascript
// the + operator
const str = "No" + " " + "capes!";
str; 
// 'No capes!'

// template literal
function intro(name, occupation) {
  console.log(`I am ${name} the ${occupation}.`)
}

intro('Megan', 'developer');
// 'I am Megan the developer.'

// concat()
const str = 'Dory said, ';
str.concat('"Just', ' ', 'keep', ' ', 'swimming"');
// 'Dory said, "Just keep swimming"'
```
**Note**: `concat()` is rarely used, since it causes more errors than the `+` operator. If you must use `concat()`, it's best to use on an empty string.

![Dory Just Keep Swimming](https://media.giphy.com/media/ml3A3OWN3sT1S/giphy.gif)
```javascript
''.concat('Just', ' ', 'keep', ' ', 'swimming');
// 'Just keep swimming'
``` 
---
### Remove Whitespace <a name="trim"></a>
Let's say if the `string` has whitespace on both ends, `trim()` is the method to remove the whitespaces.
![Woody](http://mrwgifs.com/wp-content/uploads/2013/11/This-Isnt-Flying-This-Is-Falling-With-Style-Quote-Gif-In-Toy-Story.gif)
```javascript
const woody = "    This isn’t flying. This is falling with style.    "

// trim()
woody.trim();
// 'This isn’t flying. This is falling with style.'
```
---
## Methods That Exist in Both String and Array <a name="common-methods"></a>

#### `concat()`

As we discussed earlier, we can use `concat()` in string. Although in my experience `concat()` is more often seen in string, turns out we can do the same with array.

`String.prototype.concat()` and `Array.prototype.concat()` have similar behavior, which are **concatenating two separate objects into one**. Let's take a look down below:

```javascript
// concat() in string
const str = 'Dory said, ';
str.concat('"Just', ' ', 'keep', ' ', 'swimming"');
// 'Dory said, "Just keep swimming"'
```

```javascript
// concat() in array
const arr1 = [1, 3, 5, 7];
const arr2 = [2, 4, 6, 8];

arr1.concat(arr2) // [1, 3, 5, 7, 2, 4, 6, 8];
```
**Note**: this method is immutable, i.e., does not change the existing arrays, but it would return a new array.

---
#### `indexOf()`

So you want to find an index of a character in a string? Well, turns out you can use the same method for array.

Let's take a look at the example:
```javascript
// String example
let findDory = "Where are Dory's parents, Dory's dad and Dory's mom?";
// returns the first index of the first occurrence of a specified text in a string 

findDory.indexOf('Dory') // 10
```
```javascript
// Array Example
const doryFriends = ['nemo', 'marlin', 'destiny', 'crush']
// returns the first index at which a given element can be found in array, otherwise, return -1.

doryFriends.indexOf('destiny'); // 2
```
**Note**: JavaScript arrays are zero-indexed, i.e. the index of the first element is 0, not 1.

---
#### `slice()`

Similar to our friend, `String.prototype.slice()`, `Array.prototype.slice()` behaves quite similar but in array. `Array.prototype.slice()` returns a shallow copy of a portion of an array into a new array from `start` to `end` (which `end` is not included. Also, it's optional, in this case, to the end of the array.) 

```javascript
// String Example
let buzzLightyear = "To infinity and beyond!"

buzzLightyear.slice(3) // 'infinity and beyond!'
buzzLightyear.slice(3, 11) // 'infinity'
```
```javascript
// Array Example
const woodyFriends = ['Buzz Lightyear', 'Jessie', 'Mr and Mrs. Potato Head', 'Slinky Dog', 'Rex'];

woodyFriends.slice(1); 
// [ 'Jessie', 'Mr and Mrs. Potato Head', 'Slinky Dog', 'Rex' ]
woodyFriends.slice(2, 4);
// [ 'Mr and Mrs. Potato Head', 'Slinky Dog' ]
```

As you can see, all three of these methods behave quite similar to their String counterpart. There are a lot of methods out there sometimes we lost track which is which, now that we know, `concat()`, `indexOf()` and `slice()` can be used in both `string` and `array`!

---
## Conclusion <a name="conclusion"></a>
Wow! You made it to the end of this article! Let's conclude what we have discussed!

- If we want to **find an individual character or index**, we use `indexOf()`, `lastIndexOf()`, `charAt()`.
- If we want to find **whether a particular substring is included**, we use `includes()`. (don't forget about the 's'!)
- If we want to **search** for a substring, we use `search()`.
- If we want to **extract** and create a new string, we use `slice()` and `substring()`.
- If we want to **replace** specific string content, we use `replace()`. Remember it is case sensitive, otherwise, we can use `/i` for any case-insensitive situation.
- If we want to **capitalize** our strings or **convert every character in a string to lower case**, we use `toUpperCase()` and `toLowerCase()` respectively.
- If we want to **concatenate** our strings, we can use the `+` operator, template literal and `concat()`.
- Last but not least, if we want to **remove the whitespace** of both ends of our strings, we use `trim()`.

Alright, that's all we got for now! Hope it helps untangle your confusion if you have any!

![Untangle String GIF](https://media.giphy.com/media/3o6nUNCph1w9w09hAc/giphy.gif)

Before you go, Waverley (remember my shoutout in the beginning?) and I have co-written our first collaborated article , which covers the [crossovers of strings and arrays]() in our ongoing Data Structures and Algorithm series. Check it out and stay tuned with our series!

P.S. I apologize for the Pixar GIFs if you are not a huge Pixar fan 🙏🏻😅

---
## Resources

- [JavaScript String Methods](https://www.w3schools.com/js/js_string_methods.asp)
- [3 Ways to Concatenate Strings in JavaScript](https://masteringjs.io/tutorials/fundamentals/string-concat)
- MDN String.prototype.[fill-in-the-blank-method]
- MDN Array.prototype.[fill-in-the-blank-method]