String Formatting and Methods

Quick Overview of Day

Working with strings in JS.

String Concatenation

Just like in Python, we can concatenate two strings together using a + sign.

Concatenation Example:

let name = "Dan";
let message = "My name is " + name + ".";
console.log(message);    // will output "My name is Dan."

Template Literals

Similar to f-strings in Python. You can evaluate variables (or anything, really) inside a template literal. Consider the examples below: MDN Template Literal Reference Page

Template Literal Example:

let name = "Dan";
let message = `My name is ${name}.`;
console.log(message);    // will output "My name is Dan."

let age = 16;
let future = `In twenty years, I'll be ${age + 20} years old.`;
console.log(future);

String Methods

MDN Strings Methods reference

The most important ones to know:

  • slice (behaves very similar to string slicing in Python)

  • split (splits a string into an array, based on separator passed in)

  • charAt (gets the character at a specific index value)

  • indexOf (searches for something inside a string)

CodingJS String Practice Problems

If you want to improve your string manipulation skills, you can try the following: