During this part of the section or at least my blog, I'll be learning and showing you about strings.
var myFirstName = "Randy"; var myLastName = "Rivera";
I created two variables myFirstName and myLastName and assigned them values.
"Randy" is called a string literal. It's a string because it is a series of zero or more characters enclosed in single or double quotes.
When you're creating a string you must start and end with a single or double quote. Although what if you need a literal quote: " or ' inside of your string?.
You can definitely use them by placing a backslash () in front of the quote.
var someStr = "My cousin said, \"Randy wants to become a programmer\".";
When you print this to the console you will get:
My cousin said, "Randy wants to become a programmer".
Code Output \' single quote \" double quote \\ backslash \n newline \r carriage return \t tab \b word boundary \f form feed
- Helpful chart.
var myStr = "I'm First. " + "I'm Second."
Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
The console would display the string I'm First. I'm Second.
Sometimes you will need to build a string, Mad Libs style. By using the concatenation operator (+), you can insert one or more variables into a string you're building.
var myName = "Randy"; var someStr = "Hello, my name is " + ourName + ", how are you?";
someStr would have a value of the string Hello my name is Randy, how are you?.
You can find the length of a String value by writing .length after the string variable or string literal.
we create a variable
var firstNameLength = 0; var firstName = "Randy";
we could find out how long the string Randy is by using the firstName.length property. Let's count the number of characters in the FirstName variable and assign it to firstNameLength.
firstNameLength = firstName.length; console.log(firstName.length) // 5