JavaScriptLoops, Arrays & Strings

Javascript String

Learn how to use Javascript strings to store and manipulate text data for web applications.

What is a JavaScript String?Link to this section

A JavaScript string is a sequence of characters used to represent text. It can contain letters, numbers, symbols, and spaces enclosed inside single quotes, double quotes, or backticks.

This example creates a string variable and prints its value to the console.

  • `let` is the variable declaration keyword
  • `userName` is the name of the string variable
  • `"Alice"` is the string value enclosed in double quotes
  • `console.log()` outputs the string to the console

Strings are used whenever you need to handle textual information in your programs.

Why Do We Need JavaScript Strings?Link to this section

Text data is essential for almost every user-facing application, from displaying usernames to showing receipts.

  • Display user profile names on a dashboard
  • Store customer email addresses during registration
  • Print item descriptions on a shopping cart receipt
  • Show error messages when a password is too short
  • Save user comments in a blog post section
  • Display city names in a weather app

Combining strings allows us to build personalized messages for users.

This example shows how strings make it easy to create dynamic text by joining variable names together with literal text.

About JavaScript StringsLink to this section

JavaScript strings are immutable, meaning once a string is created, its characters cannot be changed directly. Instead, methods return new strings with the desired changes. You can create them using single quotes, double quotes, or backticks for template literals.

Quote TypeSyntax ExampleMain Feature
Single Quotes'Hello'Basic text representation
Double Quotes"Hello"Basic text representation
Backticks`Hello`Allows variable interpolation and multi-line strings

Strings cannot be modified in place. The assignment above fails silently or throws an error in strict mode.

Types of String Operations and MethodsLink to this section

1. String Length and IndexingLink to this section

Every string has a length property and individual characters can be accessed using zero-based indexing.

Indices start at 0 and go up to length - 1.

note

The last character of any string is always at index `string.length - 1`.

warning

Trying to access an index beyond the string length returns undefined, not an error.

2. Finding SubstringsLink to this section

Methods like indexOf, lastIndexOf, and includes help you search for specific text inside a string.

indexOf returns the starting index of the match, or -1 if not found.

tip

Use `includes()` when you only need a true or false answer about whether text exists.

3. Extracting Parts of a StringLink to this section

You can extract portions of a string using slice, substring, or substr methods.

slice extracts from the start index up to, but not including, the end index.

note

The `slice()` method accepts negative numbers to count from the end of the string.

4. Changing CaseLink to this section

toUpperCase and toLowerCase methods let you convert all letters in a string to uppercase or lowercase.

Normalizing case is crucial when comparing user emails or usernames.

tip

Always convert user input to lowercase before checking it against a database of stored usernames.

5. Replacing ContentLink to this section

The replace and replaceAll methods allow you to swap specific words or characters inside a string.

Standard replace only changes the first match.

warning

To replace all matches without regular expressions, use `replaceAll()` instead of `replace()`.

6. Trimming WhitespaceLink to this section

The trim method removes extra spaces from both the beginning and the end of a string.

Trimming is essential for cleaning form inputs before saving them.

note

You can also use `trimStart()` or `trimEnd()` if you only want to remove spaces from one side.

7. Splitting StringsLink to this section

The split method divides a string into an array of smaller strings based on a separator.

Splitting is very useful when parsing CSV files or comma-separated lists.

tip

Passing an empty string `""` to `split()` splits the string into individual character elements.

8. Template LiteralsLink to this section

Template literals use backticks to embed variables and expressions directly inside strings.

Variables are placed inside ${} within backticks.

note

Template literals also support multi-line strings without needing newline escape characters like `\n`.

Escape CharactersLink to this section

Escape characters use a backslash to include special characters like quotes or newlines inside strings.

The backslash tells JavaScript to treat the inner quotes as literal characters.

note

Common escape sequences include `\n` for a new line and `\t` for a tab space.

Complete Coding ExampleLink to this section

This complete program normalizes messy user name inputs into a neat capitalized format.

This script cleans, formats, and combines separate first and last name variables into a single neat display string.

Important NotesLink to this section

  • JavaScript strings are immutable and cannot be changed in place.
  • String indexing starts at 0 and ends at length - 1.
  • Use single quotes, double quotes, or backticks to create strings.
  • Backtick template literals allow easy variable interpolation with `${}`.
  • The length property returns the number of characters in a string.
  • Use `trim()` to remove unwanted whitespace from both ends of a string.
  • Use `toLowerCase()` and `toUpperCase()` to standardize text casing.
  • The `includes()` method checks if a substring exists within a string.
  • Use `split()` to convert a string into an array of substrings.
  • Escape characters like `\n` allow special formatting inside text.

SummaryLink to this section

In this lesson, you learned how to create and manipulate JavaScript strings using various built-in methods and properties. You explored indexing, searching, slicing, and formatting text for real-world scenarios. Mastering strings is a fundamental step toward building interactive web applications that handle user input.

Check Your UnderstandingLink to this section

Javascript String quiz
Question 1 of 6

What is the index of the first character in a JavaScript string?

Practice ChallengesLink to this section

1. Initials Generator

easy

Create a program with a variable containing a full name like "John Doe". Extract the first letter of the first name and the first letter of the last name, then combine them in uppercase to print the initials.

Expected output

JD

Hint: Use index 0 for the first name and find the index after the space for the last name.

2. Email Domain Checker

easy

Create a program with an email string like "student@school.edu". Use string methods to verify if the email includes the domain "@school.edu" and print the result.

Expected output

true

Hint: Use the includes method.

3. Username Cleaner

medium

Create a program with a messy username string like " Admin_User ". Trim the whitespace and convert the entire string to lowercase.

Expected output

admin_user

Hint: Chain the trim and toLowerCase methods together.

4. File Extension Extractor

medium

Create a program with a filename string like "document.pdf". Use the slice method along with indexOf to extract and print just the file extension.

Expected output

pdf

Hint: Find the index of the dot and slice from that index plus one.

5. Sentence Word Counter

hard

Create a program with a sentence string containing multiple words separated by spaces. Use the split method to count and print the total number of words in the sentence.

Expected output

4

Hint: Splitting by space creates an array whose length is the word count.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion