Strings are Things
A String
represents a sequence of char
s. It allows us to call methods (send messages) to manipulate that sequence of char
s and create new String
s.
Today, we'll show you some of the ways that you can do that.
Nothing to do with cats
When we use the operator +
with String
s, we call this concatenation. It's not adding them as we would add numbers, but it's appending one String
to another, resulting in a longer String
. JavaScript knows how to turn literals into String objects, so it does that for us behind the scenes, saving us a bit of work. What would this display?
const numberOfSuits = 4;
console.log("I have " + numberOfSuits + " suits.");
Courtesy of Brainless Tales
Template Literals
Template literals are a more readable way to concatenate String
s with other values in JS.
console.log(`I have ${numberOfSuits} suits.`);
Note that instead of having to close the String
s and add +
operators, we simply wrap the variable in ${}
.
Just in Case
Methods we call on Strings create and return new Strings rather than changing the original String. Strings in JavaScript are immutable. A common need is to convert a String to all uppercase or all lowercase:
const myGreeting = "Hello";
console.log(myGreeting.toUpperCase()); // print "HELLO"
console.log(myGreeting.toLowerCase()); // prints "hello"
console.log(myGreeting); // prints "Hello"
Sensitivity Training
We often use one of these methods to normalize user input. If we're asking for a color and call the toLowerCase()
method on the user's response before comparing it to "red", the user can type "RED", "Red", or "red" and it won't matter.
const input = require("readline-sync");
const response = input.question("Enter a color, please.");
if (response.toLowerCase() === "red") {
console.log("Roses can be red. Also, lilies.");
}
Length
A String's length()
method will tell us how many characters it contains.
const palindrome = "A dog, a panic, in a pagoda";
const palindromeLength = palindrome.length();
console.log(`${palindrome} has ${palindromeLength} characters.`);
Escape!
Sometimes we need special characters in Strings. The obvious example is a quotation mark. Quotation marks are what open and close Strings, so how would we include a quotation mark in a String? We do something called escaping. We refer to the backslash (\
) we use as an escape character.
console.log('Phil said, "You\'ve got red on you".');
We can also use escaping to insert special characters like newlines (\n
) and tabs (\t
):
console.log("This is the first line.\nSecond line");
console.log("\tThis line is indented.");
Other Useful Methods
method | description | example | result |
---|---|---|---|
trim |
trims the whitespace from the beginning and end of a String ; useful for cleaning up user input |
" bar ".trim() |
"bar" |
charAt |
returns the char at the specified (zero-based) index |
"bar".charAt(2) |
'r' |
indexOf |
returns the index of the first occurence of a substring in this String |
"foo bar baz".indexOf("bar") |
4 |
Moar Useful Methods
method | description | example | result |
---|---|---|---|
contains |
indicates whether this String contains a substring |
"foobarbaz".contains("ba") |
true |
startsWith |
indicates whether this String starts with another |
"foo".startsWith("f") |
true |
endsWith |
indicates whether this String ends with another |
"baz".endsWith("az") |
true |
substring |
returns a substring starting at the specified index, optionally including an end index | "hello".substring(1) |
|
"hello".substring(1, 4) |
"ello" |
"ell"
Let's do it!
- Use the
toLowerCase()
method with some of your previous exercises to ignore case while looking at the user's response. - Ask the user for her first name and last name. Use the
length()
method to tell her which is longer. - Ask the user for her first name and last name, then print her full name, including the necessary space between first and last name.
- Ask the user to answer your riddle. Use the appropriate method to examine the answer, ignoring case. (You supply the riddle. Finding one is half the fun.)
Let's do it moar!
- Ask the user for two Strings. Check and see if the two Strings are equal to each other. If they are, inform the the user that the Strings are equal; otherwise, inform the user that the Strings are not equal. - Change your code so that it ignores case in the comparison.
- Ask the user to create a password. Then have the user enter the password again to verify there were no typing errors. Display a message if the user properly or improperly matched their password entries.
- Ask the user to create a user name. Make sure the user name is at least 8 characters in length and that the user name contains the word "code" somewhere regardless of case. Greet the user by their user name if it is properly entered, otherwise ask the user to try again.