Strings and Template Literals

A string is a way of storing and changing text in programming languages. To indicate to JavaScript that some text is a string, use single or double quotes.

String Methods

.length

This will count the amount of characters within a string (including spaces).

let animal = "cats and dogs";
animal.length;
console.log(animal.length); // 13

.slice()

This will grab a part of the string and return it as a new string. It takes two parameters, one being the starting point, the other being the ending point. If no ending point is mentioned, it will grab everything to the right of the starting point.

let animal = "cats, dogs, birds";
let favAnimal = animal.slice(6, 10);
console.log(favAnimal);
// Will display "dogs"

.replace()

This will replace a value in a string with another value, returning a new string. This will only replace the first value and is case sensitive.

let text = "SpinSpire is great!";
let newText = text.replace("great", "amazing");
console.log(newText);
// SpinSpire is amazing!

.toUpperCase() and .toLowerCase()

Converting everything to upper or lowercase.

let text = "SpinSpire";
let textTwo = text.toUpperCase();
console.log(textTwo);
// SPINSPIRE

let textThree = "SpinSpire";
let textFour = textThree.toLowerCase();
console.log(textFour);
// spinspire

.concat()

This will join two strings together. This can be used instead of the + operator.

let textOne = "SpinSpire";
let textTwo = "example";
let textThree = textOne.concat(" ", textTwo);
console.log(textThree);
// SpinSpire example

Template Literals

Template literals are perfect for creating dynamic strings. They use backticks instead of quotes and allow embedded expressions using ${}.

const food = {
    name: "blueberry",
    color: "blue"
};
const foodDescription = `${food.name} is ${food.color}`;
console.log(foodDescription);
// "This blueberry is blue."

Template literals make code more concise and easier to read compared to string concatenation.