🧡 Strings β€” JavaScript

Home: Interview Prep Index

JavaScript strings are immutable primitive values. All string methods return new strings β€” you cannot modify a string in place. For character-by-character work, convert to an array with split('') or Array.from(s).


Subtopics

#TopicDescription
01String BasicsCreation, access, slicing, charCode, template literals
02JS String MethodsindexOf, slice, split, includes, replaceAll and more
03PatternsTwo pointers, sliding window, palindromes, stack
04Top 25 Interview QuestionsSolved problems with 5-step approach sections

The Big Picture

STRINGS IN JAVASCRIPT
β”‚
β”œβ”€β”€ Basics                ← length, access, slice, charCode
β”‚   β”œβ”€β”€ s.length
β”‚   β”œβ”€β”€ s[i], s.charAt(i)
β”‚   β”œβ”€β”€ s.slice(start, end)
β”‚   └── s.charCodeAt(i), String.fromCharCode(n)
β”‚
β”œβ”€β”€ Built-in Methods      ← JS standard library
β”‚   β”œβ”€β”€ indexOf / lastIndexOf / includes
β”‚   β”œβ”€β”€ startsWith / endsWith
β”‚   β”œβ”€β”€ toUpperCase / toLowerCase
β”‚   β”œβ”€β”€ trim / trimStart / trimEnd
β”‚   β”œβ”€β”€ split / join (array method)
β”‚   β”œβ”€β”€ replace / replaceAll
β”‚   β”œβ”€β”€ repeat / padStart / padEnd
β”‚   └── match / matchAll / search
β”‚
β”œβ”€β”€ Patterns              ← DSA on strings
β”‚   β”œβ”€β”€ Two Pointers      ← reverse, palindrome
β”‚   β”œβ”€β”€ Sliding Window    ← longest no-repeat, min window
β”‚   β”œβ”€β”€ Hashing           ← anagram, frequency count
β”‚   └── Stack             ← valid parentheses, decode
β”‚
└── Interview Questions   ← Top 25 problems

Complexity Cheat Sheet

OperationTimeNotes
s.lengthO(1)Cached property
s[i]O(1)Direct access
s + t (concat)O(n+m)New string created
s.slice(i,j)O(j-i)
s.indexOf(t)O(nΓ—m)Naive search
s.split('')O(n)Creates array
arr.join('')O(n)
s.repeat(k)O(nΓ—k)

PHP vs JS String Syntax

OperationPHPJavaScript
Lengthstrlen($s)s.length
Access char$s[$i]s[i] or s.charAt(i)
Substringsubstr($s, 1, 3)s.slice(1, 4)
Findstrpos($s, 'x')s.indexOf('x')
Reversestrrev($s)s.split('').reverse().join('')
Splitstr_split($s)s.split('') or Array.from(s)
Joinimplode('', $arr)arr.join('')
Upperstrtoupper($s)s.toUpperCase()
Containsstr_contains($s, 'x')s.includes('x')
Starts withstr_starts_withs.startsWith('x')
Ends withstr_ends_withs.endsWith('x')
ASCIIord($c)s.charCodeAt(i)
Char from intchr($n)String.fromCharCode(n)
Repeatstr_repeat($s, 3)s.repeat(3)
Padstr_pad($s, 5, '0', STR_PAD_LEFT)s.padStart(5, '0')