JavaScript Strings

What are strings?

Strings are a data type used to represent text and store them within quotes. They are sequences of characters enclosed in single quotes ' ', double quotes " ", or backticks (`). Strings can contain letters, numbers, symbols, and spaces.


Examples:

%%html
<div id="demo"></div>

<script>
    (() => {

        let carName = "Toyota";
        let carModel = 'Corolla';
        const Grandma = `Grandma`;
        console.log(carName), console.log(carModel), console.log(Grandma);
        document.getElementById("demo").innerText = carName + " " + carModel + " and " + Grandma;
        
    })();
</script>

Strings contain information about variables that are defined using let or const. To print these strings, using console.log() will print the strings in the console.


Strings and Quotes

  • Strings can work with both single and double quotes, there is no difference.
  • Strings are meant to be stored in variables. “Let” and “const” are common variables that store strings.
  • Strings can also include quotes inside quotes, but the quotes inside need to be different than the quotes outside.
let button1 = "Grandma";
let button2 = '67 Cookie';
let button3 = '"Mega Cookie"';

Counting Strings

  • Strings have a unique feature of being able to count the number or characters or how long the string is
  • Use .length to find the amount of characters a string has
  • Strings count the amount of spaces inside too
  • Strings can have 0 characters in them
%%javascript

let multiplier1 = "x100";
console.log(multiplier1.length); // Output: 4

let multiplier2 = " x100 ";
console.log(multiplier2.length); // Output: 6 (includes spaces)

let emptyString = "";
console.log(emptyString.length); // Output: 0

Simple Text Modifications

Strings can undergo some simple text modifications, including:

  • Upper case
  • Lower case

Using .toUpperCase or .toLowerCase alongside the console.log can print the following strings in the console with modified text.

Examples of Modifications

%%javascript

let name = "Cookie";
console.log(name.toUpperCase()); // "COOKIE"
console.log(name.toLowerCase()); // "cookie"
<IPython.core.display.Javascript object>

Concatenation

Strings in JavaScript can ba concatenated, which when printed in the console log, are added together.

Concatenation makes it easy to form sentences from the defined variables with strings. A mix of strings and variables defined wtih strings can make simple sentences in the console.

%%javascript
// Concatenation
let cookieName = "Chocolate Chip Cookie";
let firstName = "LeBron";
let lastName = "James";
console.log(firstName + " " + lastName + "' favorite cookie is his signature " + cookieName + "."); // "Lebron James' favorite cookie is his signature Chocolate Chip Cookie.""
<IPython.core.display.Javascript object>

Concatenation makes combining strings into sentences possible. However, concatenation can be made simpler, as it can sometimes seem very cluttered when there are multple strings needed to be combined. It is easy to lose track of quotes and addition signs.

How can we make concatenation more simpler? The answer is in template literals.


Strings and Template Literals

What are template literals?

  • Template literals are enclosed by backticks (``)
  • Template literals (introduced in ES6) have many new features added to strings. 2 of them are:
      1. Can create multi-line strings
        • Strings can be written across multiple lines
      1. String interpolation
        • Concatenation made simpler, less addition signs in place of a syntax

Example of Multi-line Strings

%%javascript
const multilineString = `
This is an example of a multi-line string.
You can write as much as you want here.
This is useful for writing paragraphs or long text.
`;
console.log(multilineString);
<IPython.core.display.Javascript object>

Example of String Interpolation

%%javascript

const name = "Lance";
console.log(`Hello, ${name}!`);
<IPython.core.display.Javascript object>

This is a great example of string interpolation in the Cookie Clicker Game.

  • It uses the syntax: ${expression} for the variables emoji, name, and price to be plugged. Template literals allow for variables to be placed inside the string.
  • The className button doesn’t need to have the backtick, but provides clarity and consistency.

Strings in Cookie Clicker Game

const Alien = {
  name: "Alien",
  emoji: "👽",
  price: 50000,
  priceIncrementer: 1.3,
  cookiesPerSecond: 500,
};

const SixSevenCookie = {
  name: "67 Cookie",
  emoji: "🤩",
  price: 67000,
  priceIncrementer: 1.5,
  cookiesPerSecond: 670,
};

const DookieCookie = {
  name: "Dookie Cookie",
  emoji: "💩",
  price: 100000,
  priceIncrementer: 1.7,
  cookiesPerSecond: 1000,
};

In this example, there are six examples of strings.

  • “Grandma”, “Chef”, and “Kitchen” are three examples are under the variable: “const”.
  • Another three examples, “👵”, “👨‍🍳”, and “🔪”, are examples of strings as emojis.

This is where you will find homework: Github Homework Link