JavaScript Strings
# 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()andsubstring().
-
Search within strings using
indexOf()andincludes().
-
Replace and format text using
replace(),toUpperCase(), andtrim().
- 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!).
4. Extracting Characters
Since strings are essentially arrays of characters, you can access individual letters using zero-indexed brackets [] or the charAt() method.
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 ${}`.
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.
Example 2: Negative slice()
If a parameter is negative, the position is counted from the end of the string.
Example 3: replace() - Swapping Text
The replace() method replaces a specified value with another value in a string.
*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().
Example 5: Changing Case (toUpperCase / toLowerCase)
Converting text is crucial when comparing user inputs (e.g., verifying an email address).
Example 6: trim() - Cleaning User Input
Users often accidentally add spaces before or after their usernames. trim() removes whitespace from both ends.
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.
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.
Example 9: includes() - Boolean Searching
Introduced in ES6, it simply returns true if a string contains a specified value, otherwise false.
Example 10: startsWith() and endsWith()
Perfect for checking file extensions or URL structures.
---
7. Common Mistakes for Beginners
- 1. Forgetting String Immutability: String methods do NOT change the original string. They return a *new* string.
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>
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.
Create a variable let str = "JavaScript"
. Console log the length of the string.
-
2.
Use the slice()
method to extract "Script" from the variable above.
-
3.
Use a Template Literal to console log a string that combines the variables let city = "Tokyo"
andlet 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()
andreplaceAll()swap text.
-
toUpperCase()
andtoLowerCase()change capitalization.
-
trim()
removes excess whitespace.
-
includes()
returns true/false if a text is found.
-
Template Literals (
`) make injecting variables (${var}`) extremely easy.