Scalable Business for Startups
Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.
Chapter 4: Strings and String Manipulation in JavaScript
Chapter Overview
Strings are essential data types in JavaScript, allowing developers to handle, format, and manipulate text. In this chapter, we’ll explore strings, how to create them, common string methods, and the different ways to manipulate text.
Table of Contents
- Introduction to Strings
- Creating Strings
- String Properties and Methods
- String Concatenation
- Template Literals
- String Comparison
- Extracting Substrings
- Searching within Strings
- Replacing Parts of a String
- Splitting Strings
- Trimming Strings
- Converting Strings
- Regular Expressions and Pattern Matching
- Common String Manipulation Examples
1. Introduction to Strings
Strings in JavaScript are sequences of characters used to store and manipulate text. JavaScript strings are immutable, which means they cannot be changed once created. When a modification is made, it creates a new string.
2. Creating Strings
Strings can be created in three main ways:
- Single quotes ('):
let greeting = 'Hello';
- Double quotes ("):
let greeting = "Hello";
- Backticks (`) for template literals:
let greeting = `Hello`;
let name = "Alice";
let singleQuote = 'This is a single-quoted string';
let doubleQuote = "This is a double-quoted string";
let templateLiteral = `Hello, ${name}!`;
3. String Properties and Methods
Strings in JavaScript have properties and methods. The most commonly used property is .length
, which returns the length of the string.
let str = "Hello, World!";
console.log(str.length); // Output: 13
4. String Concatenation
You can combine strings using the +
operator or template literals.
let firstName = "Alice";
let lastName = "Johnson";
let fullName = firstName + " " + lastName; // Using +
let fullNameTemplate = `${firstName} ${lastName}`; // Using template literals
5. Template Literals
Template literals (backticks) allow embedding expressions and multi-line strings.
let age = 25;
let message = `I am ${age} years old.`;
console.log(message); // Output: I am 25 years old.
6. String Comparison
JavaScript strings can be compared using ==
, ===
, <
, >
, etc.
let str1 = "apple";
let str2 = "banana";
console.log(str1 < str2); // Output: true (lexical comparison)
7. Extracting Substrings
Methods to extract parts of strings include:
.slice()
.substring()
.substr()
(not recommended)
let str = "JavaScript";
console.log(str.slice(0, 4)); // Output: Java
console.log(str.substring(4, 10)); // Output: Script
8. Searching within Strings
You can find the index of a substring with:
.indexOf()
.lastIndexOf()
.includes()
(returnstrue
orfalse
)
let str = "Hello, World!";
console.log(str.indexOf("World")); // Output: 7
console.log(str.includes("Hello")); // Output: true
9. Replacing Parts of a String
The .replace()
method allows you to replace part of a string with another value.
let str = "Hello, World!";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // Output: Hello, JavaScript!
10. Splitting Strings
You can split strings into arrays with .split()
.
let str = "apple,banana,cherry";
let fruits = str.split(",");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
11. Trimming Strings
Use .trim()
, .trimStart()
, or .trimEnd()
to remove whitespace.
let str = " Hello, World! ";
console.log(str.trim()); // Output: "Hello, World!"
12. Converting Strings
Convert a string to uppercase or lowercase with .toUpperCase()
and .toLowerCase()
.
let str = "Hello, World!";
console.log(str.toUpperCase()); // Output: HELLO, WORLD!
console.log(str.toLowerCase()); // Output: hello, world!
13. Regular Expressions and Pattern Matching
JavaScript allows powerful text manipulation with regular expressions (RegExp
).
let str = "Hello, World!";
let result = str.match(/world/i); // Case-insensitive search
console.log(result); // Output: ["World"]
14. Common String Manipulation Examples
Reverse a String
let str = "JavaScript";
let reversed = str.split("").reverse().join("");
console.log(reversed); // Output: tpircSavaJ
Capitalize Each Word
let str = "hello world";
let capitalized = str.split(" ").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
console.log(capitalized); // Output: Hello World
Summary
In this chapter, we’ve covered the basics of string creation, common methods, and a variety of ways to manipulate strings in JavaScript. Mastering string manipulation is fundamental for handling user input, formatting data, and much more in JavaScript programming.