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
- Extract String Parts
- Replace String Content
- All Lower Cases <=> All Upper Cases
- Concatenation
- Remove Whitespace
- Methods That Exist in Both String and Array
- Conclusion
Find a String in a String
indexOf()
, lastIndexOf()
, charAt()
and search()
are the go-to methods.
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 π
)
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
slice()
and substring()
are the go-to methods. (Not going to cover substr()
since it is going to be a legacy method.)
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 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'
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.
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
There are a few ways to concat strings:
- the
+
operator - template literal
-
concat()
// 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.
''.concat('Just', ' ', 'keep', ' ', 'swimming');
// 'Just keep swimming'
Remove Whitespace
Let's say if the string
has whitespace on both ends, trim()
is the method to remove the whitespaces.
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
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"'
// 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:
// 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
// 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.)
// String Example
let buzzLightyear = "To infinity and beyond!"
buzzLightyear.slice(3) // 'infinity and beyond!'
buzzLightyear.slice(3, 11) // 'infinity'
// 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
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()
andsubstring()
. - 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()
andtoLowerCase()
respectively. - If we want to concatenate our strings, we can use the
+
operator, template literal andconcat()
. - 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!
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
- 3 Ways to Concatenate Strings in JavaScript
- MDN String.prototype.[fill-in-the-blank-method]
- MDN Array.prototype.[fill-in-the-blank-method]
Top comments (0)