Day 14: Strings and JSON
Lesson 2: String Methods
Strings are primitive types but they still come with a host of functions (aka methods) and properties that you can call on them. Let's rattle though the most common here.
You've already seen this one,
.length tells you the number of characters in the string. This is a property not a method, so you don't use
() with it.
Let's you slice out a portion of a string between two indexes (positions)
If you omit the second number then it just runs to the end of the string. Take the 7 out from the above (don't forget to remove the comma as well)
If you make the numbers negative then they count back from the end of the string. So
slice(-1) gives you the last character. Change the above playground to get the last 4 characters.
It's important to note that
slice gives you a new string and leaves the string you applied it to alone. Log out
name above to see what I mean.
If you want to replace the first instance of something in a string then
replace is your friend.
.replace() is case sensitive. So in the above
replace("the","We") won't work.
You can also use Regular Expressions in
replace, we won't be going into them in this course though, so this is just a thing for you to be aware of.
Not added until 2021,
replaceAll() is the the same as
replace except it does all instances.
.toUpperCase() and .toLowerCase()`
You can change the case of a string with these two methods. Most commonly I will use
toLowerCase() when I want to validate user input against some value where casing isn't important.
Speaking of user validation. It's surprisingly common for people to enter extra white space when filling in forms. This can cause odd behavior - imagine the above example if the user had entered 'Italy '?!
So we have the trim methods. We can
trim() which removes whitespace at the start and end of a string,
trimEnd() which takes it off the end and
trimStart() which takes it off the beginning.
And now we get something we can test against.
.toLowerCase() returns a new string I could have done this:
1const cleanedDestination = destination.toLowerCase().trim(); 2const result = validCountries.includes(cleanedDestination);
Try adding this into the playground above.
One of the most used string functions is
.split(). It lets you split a string into an array based on a certain character.
Very commonly you will use this on URLs or file paths and split on
/ or when when working with comma separated data and split on the
Very often when you are in a coding interview you will be tasked dealing with strings and very often the first thing you will do is call
.split() in some way to get it into more manageable data.
Arrays have a handy method on them called
.join() that let's you do the reverse of
.split() you can really start do some powerful manipulations.