Lesson 8: Mastering JavaScript Strings (PART-2)

manoj ymkmanoj ymk
4 min read

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

PropertyDescriptionExample
lengthReturns 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

MethodDescriptionExample
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

MethodDescriptionExample
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

MethodDescriptionExample
toLowerCase()Converts to lowercase"HELLO".toLowerCase()
toUpperCase()Converts to uppercase"hi".toUpperCase()

๐Ÿ”น ๐Ÿงฝ 4. Cleaning Up Text

MethodDescriptionExample
trim()Removes spaces from both ends" abc ".trim()
trimStart()Removes leading spaces" abc ".trimStart()
trimEnd()Removes trailing spaces" abc ".trimEnd()

๐Ÿ”น ๐Ÿงฑ 5. Modifying & Constructing

MethodDescriptionExample
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

MethodDescriptionExample
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

MethodDescriptionExample
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

MethodDescriptionExample
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

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk