JavaScript Strings
Learn how to work with strings in JavaScript, create them, access characters, use common string methods, and perform everyday text manipulation.
Reading Time
18 min
Lesson
Lesson 15 of 48
What is a String?
A string is a sequence of characters used to represent text. Strings can contain letters, numbers, symbols, and spaces. In JavaScript, strings are enclosed in single quotes, double quotes, or backticks.
Creating Strings
Console Output
Click “Run” to see the console output here.
Accessing Characters
Each character in a string has an index starting from 0. You can access characters using square brackets or the charAt() method.
Access Characters
Console Output
Click “Run” to see the console output here.
String Length
The length property returns the total number of characters in a string.
Finding String Length
Console Output
Click “Run” to see the console output here.
Common String Methods
JavaScript provides many built-in methods for searching, modifying, and extracting text.
Popular String Methods
| Method | Description |
|---|---|
| toUpperCase() | Converts string to uppercase |
| toLowerCase() | Converts string to lowercase |
| trim() | Removes whitespace from both ends |
| includes() | Checks if text exists |
| startsWith() | Checks beginning of string |
| endsWith() | Checks end of string |
| slice() | Extracts part of a string |
| replace() | Replaces text |
| split() | Converts string into an array |
Using String Methods
Console Output
Click “Run” to see the console output here.
Template Literals
Template literals use backticks and allow variables and expressions to be embedded using ${}. They also support multi-line strings.
Template Literal Example
Console Output
Click “Run” to see the console output here.
Splitting a String
The split() method divides a string into an array using a specified separator.
split() Example
Console Output
Click “Run” to see the console output here.
Joining Strings
Strings can be combined using the + operator or template literals. Template literals are preferred because they are more readable.
Concatenation
Console Output
Click “Run” to see the console output here.
Best Practice
Prefer template literals over string concatenation because they are easier to read and maintain, especially when working with variables.