String
Welcome to the String section of JDCodebase! Strings are a fundamental data type used to represent sequences of characters. Many interview problems are based on efficient string manipulation, pattern matching, and transformation.
What You’ll Learn
- Basic string manipulation: concatenation, slicing, length
- Two-pointer and sliding window approaches
- Reversing, capitalizing, and formatting strings
- Checking palindromes, anagrams, and patterns
- Working with character frequency and hashing
JavaScript String Methods
str.length: Returns the length of the string.
Before: "hello".length Code: str = "hello"; str.length; After: 5
str.charAt(index): Returns the character at the specified index.
Before: "hello" Code: str.charAt(1); After: "e"
str.slice(start, end): Extracts a section of the string and returns it.
Before: "hello world" Code: str.slice(0, 5); After: "hello"
str.substring(start, end): Returns the substring between two indexes.
Before: "hello world" Code: str.substring(6); After: "world"
str.toUpperCase(): Converts the string to uppercase letters.
Before: "hello" Code: str.toUpperCase(); After: "HELLO"
str.toLowerCase(): Converts the string to lowercase letters.
Before: "HELLO" Code: str.toLowerCase(); After: "hello"
str.includes(substr): Checks if a substring exists within the string.
Before: "hello world" Code: str.includes("world"); After: true
str.replace(old, new): Replaces part of the string with another string.
Before: "Hello World" Code: str.replace("World", "JS"); After: "Hello JS"
str.split(delimiter): Splits the string into an array by delimiter.
Before: "a,b,c" Code: str.split(","); After: ["a", "b", "c"]
str.trim(): Removes whitespace from both ends of the string.
Before: " hello " Code: str.trim(); After: "hello"
Try This Example
Check if a string is a palindrome.
function isPalindrome(str) { let left = 0; let right = str.length - 1; while (left < right) { if (str[left] !== str[right]) return false; left++; right--; } return true; }
Input: "racecar"
Expected Output: true