Skip to main content
JavaScript Basics
CHAPTER 12 Beginner

JavaScript Strings

Updated: May 12, 2026
20 min read

# JavaScript Strings

Strings are used for storing and manipulating text. Whether you are validating a user's email address, formatting a tweet, or searching for a keyword in a blog post, you are working with Strings.

In this chapter, we will explore the powerful built-in methods JavaScript provides to manipulate text.

1. Introduction

A JavaScript string is zero or more characters written inside quotes. While you can just print strings, their real power comes from String Methods—built-in functions that allow you to search, slice, replace, and format text effortlessly without having to write complex logic yourself.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use string length and extract specific characters.
  • Use Template Literals (Backticks) for clean string formatting.
  • Extract parts of a string using slice() and substring().
  • Search within strings using indexOf() and includes().
  • Replace and format text using replace(), toUpperCase(), and trim().
  • Build a working Username Formatter mini-project.

3. String Quotes and Length

You can use single quotes '' or double quotes "". They work identically.

To find the length of a string, use the built-in length property (just like arrays!).

javascript
123
// Example
let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(txt.length); // Output: 26

4. Extracting Characters

Since strings are essentially arrays of characters, you can access individual letters using zero-indexed brackets [] or the charAt() method.

javascript
1234
// Example
let str = "HELLO";
console.log(str[0]); // Output: H
console.log(str.charAt(1)); // Output: E

5. Template Literals (ES6)

Before 2015, combining variables and strings (concatenation) was a nightmare of plus signs and quotes. Template Literals use backticks (` `) and allow you to inject variables directly into the string using ${}`.

javascript
123456789
// Example
let firstName = "John";
let age = 30;

// Old Way (Concatenation)
let oldWay = "My name is " + firstName + " and I am " + age + " years old.";

// New Way (Template Literal)
let newWay = `My name is ${firstName} and I am ${age} years old.`;

Template literals also allow multi-line strings without needing \n.

---

6. Real-world Examples & Code Snippets

Example 1: slice() - Extracting a Substring

slice(start, end) extracts a part of a string and returns it as a new string. The end index is not included.

javascript
12345
// Example JavaScript
let fruits = "Apple, Banana, Kiwi";
let part = fruits.slice(7, 13);

console.log(part); // Output: Banana

Example 2: Negative slice()

If a parameter is negative, the position is counted from the end of the string.

javascript
123456
// Example JavaScript
let msg = "I love JavaScript";
// Start 10 characters from the end
let extracted = msg.slice(-10);

console.log(extracted); // Output: JavaScript

Example 3: replace() - Swapping Text

The replace() method replaces a specified value with another value in a string.

javascript
12345
// Example JavaScript
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Google");

console.log(newText); // Output: Please visit Google!

*Note: replace() only replaces the FIRST match it finds. It is case-sensitive.*

Example 4: replaceAll()

If you want to replace every instance of a word, use replaceAll().

javascript
12345
// Example JavaScript
let text = "Cats are great. Cats are fluffy.";
let newText = text.replaceAll("Cats", "Dogs");

console.log(newText); // Output: Dogs are great. Dogs are fluffy.

Example 5: Changing Case (toUpperCase / toLowerCase)

Converting text is crucial when comparing user inputs (e.g., verifying an email address).

javascript
12345
// Example JavaScript
let text = "Hello World!";

console.log(text.toUpperCase()); // Output: HELLO WORLD!
console.log(text.toLowerCase()); // Output: hello world!

Example 6: trim() - Cleaning User Input

Users often accidentally add spaces before or after their usernames. trim() removes whitespace from both ends.

javascript
123456
// Example JavaScript
let badInput = "     coder99    ";
let cleanInput = badInput.trim();

console.log("Original length:", badInput.length); // Output: 16
console.log("Clean length:", cleanInput.length);   // Output: 7

Example 7: split() - String to Array

A string can be converted to an array using the split() method. You tell it what character to "split" on.

javascript
123456
// Example JavaScript
let csvData = "John,Doe,35,New York";
let dataArray = csvData.split(",");

console.log(dataArray[0]); // Output: John
console.log(dataArray[3]); // Output: New York

Example 8: indexOf() - Searching for Text

Returns the index of the first occurrence of a specified text in a string. Returns -1 if not found.

javascript
1234
// Example JavaScript
let str = "Please locate where 'locate' occurs!";
console.log(str.indexOf("locate")); // Output: 7
console.log(str.indexOf("pizza"));  // Output: -1

Example 9: includes() - Boolean Searching

Introduced in ES6, it simply returns true if a string contains a specified value, otherwise false.

javascript
12345
// Example JavaScript
let sentence = "The quick brown fox jumps over the lazy dog.";

console.log(sentence.includes("fox")); // Output: true
console.log(sentence.includes("cat")); // Output: false

Example 10: startsWith() and endsWith()

Perfect for checking file extensions or URL structures.

javascript
123456
// Example JavaScript
let url = "https://tutorialspoint.com";
let file = "image.png";

console.log(url.startsWith("https")); // Output: true
console.log(file.endsWith(".jpg"));   // Output: false

---

7. Common Mistakes for Beginners

  1. 1. Forgetting String Immutability: String methods do NOT change the original string. They return a *new* string.
javascript
1234567891011121314151617181920
   let name = "john";
   name.toUpperCase(); // This calculates "JOHN", but throws it into the void!
   console.log(name);  // Output: "john"

   // Correct way:
   name = name.toUpperCase();
   ```
2. **Case Sensitivity:** `indexOf("apple")` will not find "Apple". Always convert user input to lowercase before searching.
3. **Confusing Backticks and Single Quotes:** `` ` `` (next to the 1 key) is for Template Literals. `'` (next to the Enter key) is a standard quote.

## 8. Best Practices

- Always use Template Literals (`` ` ``) instead of concatenation (`+`) when mixing variables and strings. It is much easier to read and prevents spacing bugs.
- Always `trim()` user input from HTML forms before saving it to a database or checking a password.

## 9. Mini Project: Username Formatter

Let's build a tool that takes messy user input, cleans it up, formats it nicely, and checks if it contains illegal characters.

**HTML:**

html <!-- Example HTML --> <!DOCTYPE html> <html> <head> <style> /* Example CSS */ .box { font-family: sans-serif; padding: 20px; border: 1px solid #ccc; width: 300px; } input { width: 100%; padding: 8px; margin-bottom: 10px; box-sizing: border-box;} button { background: #007bff; color: white; padding: 10px; border: none; cursor: pointer; width: 100%;} #output { margin-top: 15px; font-weight: bold; } .error { color: red; } .success { color: green; } </style> </head> <body>

<div class="box"> <h3>Create Username</h3> <input type="text" id="userInput" placeholder=" Enter username... "> <button onclick="formatUsername()">Submit</button> <p id="output"></p> </div>

<script src="formatter.js"></script> </body> </html>

1
**formatter.js:**

javascript // Example JavaScript function formatUsername() { let rawInput = document.getElementById("userInput").value; let outputDiv = document.getElementById("output");

// 1. Remove surrounding whitespace let cleanString = rawInput.trim();

// 2. Check for empty submission if (cleanString.length === 0) { outputDiv.innerHTML = "Username cannot be empty!"; outputDiv.className = "error"; return; }

// 3. Convert to lowercase let formattedName = cleanString.toLowerCase();

// 4. Replace any spaces inside the name with underscores formattedName = formattedName.replaceAll(" ", "_");

// 5. Check for illegal characters (like @) if (formattedName.includes("@")) { outputDiv.innerHTML = "Username cannot contain '@' symbol!"; outputDiv.className = "error"; return; }

// Success! Output using Template Literals outputDiv.innerHTML = Welcome, @${formattedName}!; outputDiv.className = "success"; } ``

10. Exercises

  1. 1. Create a variable let str = "JavaScript". Console log the length of the string.
  1. 2. Use the slice() method to extract "Script" from the variable above.
  1. 3. Use a Template Literal to console log a string that combines the variables let city = "Tokyo" and let temp = 22.

11. MCQs (Multiple Choice Questions)

Q1: Which method removes whitespace from the start and end of a string? A) strip() B) clean() C) trim() D) slice() *Answer: C*

Q2: What is the output of "HELLO".toLowerCase()? A) hello B) Hello C) HELLO D) hELLO *Answer: A*

Q3: Which punctuation mark is used for Template Literals? A) "" (Double Quotes) B) '' (Single Quotes) C) ` (Backticks) D) () (Parentheses) *Answer: C*

12. Interview Questions

Q: Explain the difference between slice() and substring(). *A: Both extract parts of a string. However, slice() accepts negative indexes (counting from the end of the string), whereas substring() treats any negative or NaN parameter as 0.*

Q: How do you convert a String into an Array, and an Array into a String? *A: To convert a String to an Array, use the split() method (e.g., str.split(",")). To convert an Array to a String, use the join() method (e.g., arr.join(",")).*

13. FAQs

Q: Does JavaScript have a Character data type like C++ (char)? *A: No. In JavaScript, a single character is simply a String with a length of 1.*

14. Summary

  • The length property returns the string size.
  • slice() extracts parts of a string.
  • replace() and replaceAll() swap text.
  • toUpperCase() and toLowerCase() change capitalization.
  • trim() removes excess whitespace.
  • includes() returns true/false if a text is found.
  • Template Literals ( `) make injecting variables (${var}`) extremely easy.

15. Next Chapter Recommendation

Strings allow us to manipulate text, but what about manipulating numbers? In the next chapter, JavaScript Numbers and Math, we will explore how to round numbers, generate random numbers, and perform complex calculations.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·