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.
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:
In the example above, each of the variables firstName
, lastName
, and job
holds a string.
Concatenation combines strings. In JavaScript, we use the +
operator for this task. It's like merging puzzle pieces. Consider the following example:
In the example above, we've combined two strings to form a new string: 'Welcome to Mars!'.
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:
The charAt
method retrieves a character from a specific position within a string. Similar to lists, the position (index) counts from 0
. Here's how you use it:
By using charAt(0)
, we've retrieved the first character of greeting
— 'H'.
The includes
and indexOf
methods are commonly used tools for exploring strings. includes
searches for a particular text within a string, while indexOf
returns its position, or -1
if there is no occurrence of the provided text:
For converting all string letters to lowercase or uppercase, JavaScript provides the toLowerCase
and toUpperCase
methods respectively:
The toLowerCase
and toUpperCase
methods convert strings to all lowercase and all uppercase, respectively.
Congratulations! You've learned how to use various JavaScript string operations: concatenation, slicing, charAt
, includes
, indexOf
, and case conversion. Now, it's time to master these skills through intriguing, hands-on practice exercises. Let's get started!
