What is a String?
1. A string is a sequence of characters enclosed in single quotes, double quotes or backticks.
2. It is a primitive data type in JavaScript.
3. Strings are immutable - once created, their characters cannot be changed.
4. The internal format for strings is always UTF-16, regardless of the page encoding.
String Indexing
- Each character in a string has a position (index) starting from 0
- The last character is at position string.length - 1
- Negative indices count from the end of the string
let str = "Hello";
// Indices: 01234
// Access characters using index
console.log(str[0]); // "H"
console.log(str[4]); // "o"
console.log(str[-1]); // undefined (use at() for negative indices)
console.log(str.at(-1)); // "o" (last character)
String Access Methods
- Square brackets []: Zero-based index access (returns undefined if out of range)
- charAt(): Returns character at index (returns empty string if out of range)
- at(): Supports both positive and negative indices
let str = "JavaScript";
// Different ways to access characters
console.log(str[0]); // "J"
console.log(str.charAt(0)); // "J"
console.log(str.at(0)); // "J"
// Out of range behavior
console.log(str[20]); // undefined
console.log(str.charAt(20)); // "" (empty string)
console.log(str.at(-1)); // "t" (last character)
console.log(str.at(-2)); // "p" (second to last)
String Characteristics
- Immutability: Individual characters cannot be changed after creation
- Case Sensitivity: String comparisons and methods are case-sensitive by default
- Unicode Support: Can contain any Unicode characters including emojis
let str = "Hello";
// Immutability
str[0] = "h"; // No effect
console.log(str); // Still "Hello"
// Case sensitivity
console.log("Hello" === "hello"); // false
// Unicode support
let text = "Hello 👋 World 🌍";
console.log(text.length); // Length includes emoji characters
console.log(text[6]); // "👋" (emoji is a single character)
Types of Strings
1. There are three types of string in JavaScript:
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
2. Single and double quotes are essentially the same.
3. Backticks allow:
- Multiline strings
- String interpolation using ${expression}
4. Example of template literals:
let name = "John";
let greeting = `Hello, ${name}!`; // Hello, John!
let multiline = `
Line 1
Line 2
Line 3
`;
String Methods
1. length
- Used to: Get the number of characters in a string
- Syntax: str.length
- Returns: number - the length of the string
let str = "Hello";
console.log(str.length); // 5
let empty = "";
console.log(empty.length); // 0
2. at(index)
- Used to: Access a character at a specific position in the string
- Syntax: str.at(index)
- Returns: string - single character at the index, or undefined if out of range
let str = "Hello";
console.log(str.at(0)); // H
console.log(str.at(-1)); // o (last character)
console.log(str.at(-2)); // l (second to last)
21. matchAll(regexp)
- Used to: Get an iterator of all matches of a regular expression
- Syntax: str.matchAll(regexp)
- Returns: iterator - containing all match objects with additional information
let str = "Test1 test2 TEST3";
// g flag is required for matchAll
// i flag for case-insensitive matching
let matches = [...str.matchAll(/test\d/gi)];
// Each match object contains:
// - The full match
// - Index where match was found
// - Input string
// - Groups (if any)
console.log(matches);
// [
// ['Test1', index: 0, input: 'Test1 test2 TEST3', groups: undefined],
// ['test2', index: 6, input: 'Test1 test2 TEST3', groups: undefined],
// ['TEST3', index: 12, input: 'Test1 test2 TEST3', groups: undefined]
// ]
// Using capture groups with g flag
let str2 = "2023-03-14 2024-01-01";
let dateMatches = [...str2.matchAll(/(\d{4})-(\d{2})-(\d{2})/g)];
dateMatches.forEach(match => {
console.log(`Full date: ${match[0]}`);
console.log(`Year: ${match[1]}, Month: ${match[2]}, Day: ${match[3]}`);
});
String Practice Questions
- How do you reverse a string in JavaScript?
- Write a function to check if a string is a palindrome.
- How do you find the first non-repeated character in a string?
- Write a function to count the occurrences of each character in a string.
- How do you check if two strings are anagrams?
- Write a function to capitalize the first letter of each word in a string.
- How do you remove duplicate characters from a string?
- Write a function to find the longest word in a string.
- How do you check if a string contains only numbers?
- Write a function to count the number of vowels and consonants in a string.
Special Characters
Escaping Special Characters
- \n - New line
- \t - Tab
- \' - Single quote (')
- \" - Double quote (")
- \` - Backtick
- \\ - Backslash
- \/ - Forward slash
- \b - Backspace
- \f - Form feed
- \r - Carriage return
Examples:
// Displaying quotes
let str1 = "He said \"Hello\""; // He said "Hello"
let str2 = 'It\'s a nice day'; // It's a nice day
let str3 = `Use \` for template`; // Use ` for template
// Displaying paths
let windowsPath = "C:\\Program Files\\Apps"; // C:\Program Files\Apps
let unixPath = "/home/user/docs"; // /home/user/docs
// Multiline strings
let multiline = "First line\nSecond line\nThird line";
/* Output:
First line
Second line
Third line */
// Mixing quotes
let html = "It\'s a \"quoted\" text";
// It's a "quoted" text
// Unicode characters
let unicode = "\u00A9 2024"; // © 2024
let emoji = "\u{1F600}"; // 😀
HTML Entity References
- " - For double quotes (")
- ' - For single quotes (')
- & - For ampersand (&)
- < - For less than (<)
- > - For greater than (>)
// In HTML/JSX
<div>She said "Hello"</div> // She said "Hello"
<div>It's working</div> // It's working
<div>Price: 10&20</div> // Price: 10&20
<div>1 < 2 && 3 > 2</div> // 1 < 2 && 3 > 2