When to Use these String Methods in JavaScript

mehmehmehlol

Megan Lo

Posted on April 23, 2021

When to Use these String Methods in JavaScript

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!. Give her some shoutout!

Without further ado, here we go!


Table of Contents


Find a String in a String

indexOf(), lastIndexOf(), charAt() and search() are the go-to methods.
Baby Dory

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

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

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

Note: This is quite similar to array's find(), match(), filter(). Check these methods out in Waverley's article!!


Extract String Parts

slice() and substring() are the go-to methods. (Not going to cover substr() since it is going to be a legacy method.)
Buzz Lightyear

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

Note 1: slice() and substring() are very similar. However, there are some subtle differences. Here's the breakdown 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 that breaks down how to utilize the alternate splice() method in string.


Replace String Content

As you can imagine, there's a built-in method called replace().

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

All Lower Cases <=> All Upper Cases

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

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

Concatenation

There are a few ways to concat strings:

  • the + operator
  • template literal
  • concat() Edna No Capes Gif
// 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"'
Enter fullscreen mode Exit fullscreen mode

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

''.concat('Just', ' ', 'keep', ' ', 'swimming');
// 'Just keep swimming'
Enter fullscreen mode Exit fullscreen mode

Remove Whitespace

Let's say if the string has whitespace on both ends, trim() is the method to remove the whitespaces.
Woody

const woody = "    This isn’t flying. This is falling with style.    "

// trim()
woody.trim();
// 'This isn’t flying. This is falling with style.'
Enter fullscreen mode Exit fullscreen mode

Methods That Exist in Both String and Array

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:

// concat() in string
const str = 'Dory said, ';
str.concat('"Just', ' ', 'keep', ' ', 'swimming"');
// 'Dory said, "Just keep swimming"'
Enter fullscreen mode Exit fullscreen mode
// 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];
Enter fullscreen mode Exit fullscreen mode

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:

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

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

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

buzzLightyear.slice(3) // 'infinity and beyond!'
buzzLightyear.slice(3, 11) // 'infinity'
Enter fullscreen mode Exit fullscreen mode
// 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' ]
Enter fullscreen mode Exit fullscreen mode

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

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

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

πŸ’– πŸ’ͺ πŸ™… 🚩
mehmehmehlol
Megan Lo

Posted on April 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related