Today, I focused on building strong fundamentals by learning and revising basic string operations in JavaScript.
Mastering string manipulation is extremely important for coding interviews, especially for product-based companies and FAANG-level roles.
Hereβs what I learned today π
π 1οΈβ£ Basic Properties
β
length
Returns the total number of characters in a string (including spaces).
"Hello".length // 5
π 2οΈβ£ Accessing Characters
β
at(index)
Returns the character at a given index.
Supports negative indexing.
"Hello".at(1) // "e"
"Hello".at(-1) // "o"
β charAt(index)
Returns the character at a given index.
β Does NOT support negative indexing.
"Hello".charAt(1) // "e"
π 3οΈβ£ Searching in Strings
β
includes(searchString, position)
Returns true or false.
"banana".includes("a") // true
"banana".includes("b", 1) // false
β indexOf(searchString, position)
Returns the first occurrence index or -1.
"banana".indexOf("a") // 1
β lastIndexOf(searchString)
Returns the last occurrence index.
"banana".lastIndexOf("a") // 5
π 4οΈβ£ Modifying Strings
β
concat()
Combines strings and returns a new string.
"Hello".concat(" ", "World")
β replace(pattern, replacement)
Replaces only the first occurrence.
"banana".replace("a", "x")
// "bxnana"
β replaceAll(pattern, replacement)
Replaces all occurrences.
"banana".replaceAll("a", "x")
// "bxnxnx"
π 5οΈβ£ Padding Methods
β
padStart(targetLength, padString)
Adds characters at the beginning.
"7".padStart(3, "0")
// "007"
β padEnd(targetLength, padString)
Adds characters at the end.
"34".padEnd(5, "*")
// "34***"
π 6οΈβ£ Pattern Matching
β
match()
Returns matched results (array) or null.
Often used with regular expressions.
"banana".match(/a/g)
// ["a", "a", "a"]
π‘ Key Learnings
- Strings are immutable in JavaScript.
- Most string methods return a new string.
- Searching methods are case-sensitive.
- Understanding return types is very important for interviews.
Consistency > Motivation π
Top comments (0)