Overview and Actualization

Hello! Today, we're going to explore some key JavaScript string operations: concatenation, slicing, charAt, includes, indexOf, toLowerCase, and toUpperCase. We'll unlock these skills through examples.

Introduction to Strings in JavaScript

Strings in JavaScript are used to store and manage text. To create a string, you can use single quotes (' '), double quotes (" "), or backticks (``). Here's an example:

let firstName = 'Tim';  // Using single quotes
let lastName = "Cook";  // Using double quotes
let job = `CEO of Apple Inc.`;  // Using backticks

console.log(firstName); // Prints: "Tim"
console.log(lastName); // Prints: "Cook"
console.log(job); // Prints: "CEO of Apple Inc."

In the example above, each of the variables firstName, lastName, and job holds a string.

String Concatenation

Concatenation combines strings. In JavaScript, we use the + operator for this task. It's like merging puzzle pieces. Consider the following example:

let planet = 'Mars';
let welcomeMessage = 'Welcome to ' + planet + '!';
console.log(welcomeMessage);  // Prints: "Welcome to Mars!"

In the example above, we've combined two strings to form a new string: 'Welcome to Mars!'.

Slicing Strings with 'substring'

Slicing involves extracting a substring (a part or segment of the string). The substring(from, to) method in JavaScript facilitates this task - it returns the substring constructed from characters at positions from, from + 1, ..., to - 1, i.e., you start from the character at the position from, and end at to, excluding it.

A version of this method substring(from), at the same time, just takes the substring from the provided character till the end.

Let's see how it works:

let message = "Hello, World!";
let slice = message.substring(1, 5); // A substring starting at character 1 to 5 (exclusive)
console.log(slice);  // Prints: "ello"

// A substring starting at character 2, till the end of the string
console.log(message.substring(2)); // Prints: "llo, World!"

// A substring starting at character 7 to 13 (exclusive)
console.log(message.substring(7, 13)); // Prints: "World!"
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal