Lesson 8: Mastering JavaScript Strings (PART-2)

In JavaScript:
Strings are primitive types but behave like objects.
All strings are immutable (any change returns a new string).
Strings are UTF-16 encoded internally (important for emoji handling).
๐งท โ Most Important String Properties
Property | Description | Example |
length | Returns number of code units in string | "hello".length โ 5 |
๐ Example:
const str = "Hello ๐";
console.log(str.length); // 7 โ because ๐ takes 2 code units
๐ง โ Most Used String Methods (Grouped by Purpose)
๐น ๐ 1. Searching & Finding
Method | Description | Example |
indexOf(substr) | First occurrence (case-sensitive) | "abc".indexOf("b") โ 1 |
lastIndexOf() | Last occurrence | "ababc".lastIndexOf("b") โ 3 |
includes() | Returns true/false if substring found | "hello".includes("ll") |
startsWith() | Checks if string begins with a substring | "hello".startsWith("he") |
endsWith() | Checks if string ends with a substring | "hello".endsWith("lo") |
๐ธ Real Use Case: Validate file extension or detect if URL starts with https
.
๐น โ๏ธ 2. Extracting & Slicing
Method | Description | Example |
slice(start, end?) | Extract part of string | "hello".slice(1,4) โ ell |
substring(start, end?) | Similar to slice but can't use negatives | |
substr(start, length) | Deprecated, but still seen in old code |
๐ Key Difference (slice vs substring):
"abcdef".slice(-2); // "ef"
"abcdef".substring(-2); // "abcdef" โ treats negatives as 0
๐น ๐ ๏ธ 3. Transforming Case
Method | Description | Example |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase() |
toUpperCase() | Converts to uppercase | "hi".toUpperCase() |
๐น ๐งฝ 4. Cleaning Up Text
Method | Description | Example |
trim() | Removes spaces from both ends | " abc ".trim() |
trimStart() | Removes leading spaces | " abc ".trimStart() |
trimEnd() | Removes trailing spaces | " abc ".trimEnd() |
๐น ๐งฑ 5. Modifying & Constructing
Method | Description | Example |
replace(find, replace) | Replace part of string | "a-b".replace("-", ":") |
replaceAll() | Replaces all matches (ES2021+) | "a-a".replaceAll("a", "b") |
repeat(n) | Repeat string n times | "ha".repeat(3) โ "hahaha" |
padStart(len, str) | Pads from start to match length | "7".padStart(2, "0") โ "07" |
padEnd(len, str) | Pads from end | "7".padEnd(3, "-") โ "7--" |
๐น ๐งจ 6. Splitting & Joining
Method | Description | Example |
split(sep) | Splits string into array by separator | "a,b,c".split(",") โ ["a","b","c"] |
join(sep) | Joins array into string | ["a","b"].join("-") โ "a-b" |
๐ธ Real Use Case: CSV processing, word counting, parsing user input.
๐น ๐งฌ 7. Character-Level Access
Method | Description | Example |
charAt(index) | Returns character at index | "abc".charAt(1) โ b |
charCodeAt(index) | UTF-16 code unit value | "A".charCodeAt(0) โ 65 |
at(index) (ES2022) | Allows negative indexing | "hello".at(-1) โ "o" |
๐ธ charAt()
is older. Use .at()
for cleaner negative-index access.
๐น ๐ 8. Comparison
Method | Description | Example |
localeCompare() | Locale-sensitive comparison | "รฉ".localeCompare("e", "en") |
== , === , < | Works lexicographically for strings | "apple" < "banana" โ true |
๐ง Tips to Remember
๐ Mnemonics:
Slice & Dice โ
slice()
helps you "cut out" portions.Start-End-Include โ
startsWith()
,endsWith()
,includes()
.TRIM your inputs โ always
trim()
when reading user data.REPLACE wisely โ use
replaceAll()
for global replacements.AT your fingertips โ use
.at()
to access characters even from the end.
๐ฏ Real World Example: Format a Price Input
function formatPrice(input) {
return input.trim().replace("โน", "").padStart(4, "0");
}
console.log(formatPrice(" โน45")); // "0045"
๐งฉ Fun Challenge:
Guess the result:
const str = "123";
console.log(str.padStart(5, "0").repeat(2));
Output:
"0012300123"
โ pad, then repeat
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
