Day 21: Consolidation 4
Lesson 1: Strings and JSON
There are three ways to make strings, with
There are some characters that you need to escape with a
\ if you want to use them in a string, these are
\ itself and if you want to use single quote in a string you started with a single quote, you need to escape it like
\' and likewise for double quote in a string you started with double quotes like this
These characters get converted into something different when escaped:
\f- Form feed
\n- New line
\r- Carriage return
\t- Horizontal tab
\v- Vertical tab
There area a number of methods (functions) you can call on a string.
To get it's length you use
.slice() gives you a section of a string between two indexes, if you don't add a second property then it will be from the first index to the end. If you use negative then it will give you the string from the end.
Using slice can you pull out and log just the name of the course in the below playground?
.replace() will replace the first instance of a substring found in your string. It is used like this
.replace('substring you dont want', 'new substring to replace it with')
In the playground below can you rename this course to "Introduction to JS" ?
.replaceAll replace every instance of a substring and not just the first like
.trimEnd() remove any white space at the ends of a string. Use the most appropriate one to clean up the string in the playground below and log it out.
.split() allows you to split a string based on any character. In the play ground below I want you to split about the lesson code for this lesson and print out the parts.
You can join strings together using the
In this playground can you create the lesson code for this lesson?
There is also the
.concat() method on all strings that can take a list of comma separated arguments and make a new string starting with the string you called
Most of the time making new strings using template literals is the way to go now.
Use the playground below to make the lesson code again but this time with a template literal.
JSON.stringify() is how you do that.
If you want to read in a string with JSON in it then you can do that with
In the playground below log out the stringified version of
car, then read it back and log it out as the new object.