JavaScriptConcepts

โ† Back to Home

JavaScript Strings

JavaScript String is a primitive, immutable, UTF-16 encoded sequence of code units. A companion String object wrapper provides methods for inspection, slicing, searching, transformation, comparison, and Unicode operations.

Strings are immutable: all operations return new strings.


1. Construction

const a = "hello";
const b = 'hello';
const c = `hello ${1 + 2}`;
const d = String("hello"); 
const e = new String("hello");

2. Indexing Semantics

const s = "Aditya";
s[0];      // "A"
s.length;  // 6

Strings cannot be mutated.


3. Character Access Methods


charAt(index) โ€” Returns the character at the specified index.

"aditya".charAt(2); // "i"

charCodeAt(index) โ€” Returns UTF-16 code unit at index.

"ABC".charCodeAt(0); // 65

codePointAt(index) โ€” Returns full Unicode code point.

"๐Œ€".codePointAt(0); // 66304

at(index) โ€” Returns character at index; supports negative indexing.

"aditya".at(-1); // "a"

4. Search & Match Operations


indexOf(sub, fromIndex?) โ€” Returns first index of sub, or -1 if not found.

"banana".indexOf("na"); // 2

lastIndexOf(sub, fromIndex?) โ€” Returns last index of sub.

"banana".lastIndexOf("na"); // 4

includes(sub, fromIndex?) โ€” Returns true if substring exists.

"javascript".includes("script"); // true

startsWith(prefix, pos?) โ€” Checks if string begins with prefix.

"aditya".startsWith("adi"); // true

endsWith(suffix, length?) โ€” Checks if string ends with suffix.

"aditya".endsWith("tya"); // true

search(regex) โ€” Returns index of first regex match.

"hello123".search(/\d/); // 5

match(regex) โ€” Returns array of matches or null.

"abc123".match(/\d+/); // ["123"]

matchAll(regex) โ€” Returns iterator over all regex matches.

[... "a1b2c3".matchAll(/\d/g)];

5. Extraction / Slicing


slice(start, end) โ€” Extracts substring; supports negative indices.

"javascript".slice(0, 4); // "java"

substring(start, end) โ€” Extracts substring; swaps reversed indices.

"javascript".substring(4, 0);

substr(start, length) โ€” Extracts substring of given length (legacy).

"javascript".substr(4, 6);

6. Transformation Methods


toUpperCase() โ€” Returns uppercased copy.

"adi".toUpperCase();

toLowerCase() โ€” Returns lowercased copy.

"ADI".toLowerCase();

trim() โ€” Removes leading & trailing whitespace.

"  x  ".trim();

trimStart() / trimEnd() โ€” Removes leading or trailing whitespace.

"  x  ".trimStart();

repeat(n) โ€” Repeats string n times.

"ha".repeat(3);

replace(searchValue, replaceValue) โ€” Replaces first match (or regex).

"banana".replace("a", "A");

replaceAll(searchValue, replaceValue) โ€” Replaces all occurrences.

"banana".replaceAll("a", "A");

padStart(targetLength, padString?) โ€” Pads the start to target length.

"5".padStart(3, "0");

padEnd(targetLength, padString?) โ€” Pads the end to target length.

"5".padEnd(3, "0");

7. Splitting

split(separator, limit?) โ€” Splits string into array.

"1,2,3".split(",");

8. Iteration

for...of โ€” Iterates by Unicode code points.

for (const ch of "aditya") console.log(ch);

String.prototype[Symbol.iterator] โ€” Underlying iterator.


9. Template Strings

Multiline literals

`
Hello
World
`

Expressions

`Total: ${2 + 3}`;

Tagged templates

tag`line1\nline2`;

10. Unicode / Normalization


normalize(form) โ€” Normalizes Unicode strings.

"\u1E9B\u0323".normalize("NFC");

Surrogate pair handling

"๐Œ€".length;      // 2
[... "๐Œ€"].length; // 1

11. Conversion

toString() โ€” Converts value to string.

(123).toString();

valueOf() โ€” Returns primitive string of wrapper.

new String("abc").valueOf();

12. Locale-Aware Comparison

localeCompare() โ€” Compares strings using locale rules.

"รค".localeCompare("z", "de");

13. Method Category Summary

Category Methods
Character charAt, charCodeAt, codePointAt, at
Search indexOf, lastIndexOf, includes, startsWith, endsWith, match, matchAll, search
Extraction slice, substring, substr
Transformation toUpperCase, toLowerCase, trim*, repeat, replace*, padStart, padEnd
Splitting split
Unicode normalize
Locale localeCompare
Iteration Symbol.iterator, for...of
Conversion toString, valueOf

14. Edge Cases

Immutability

All string operations create new strings.

slice vs. substring

Unicode pitfalls

UTF-16 code units cause "๐Ÿ˜€".length === 2.

Regex replace function

"123".replace(/\d+/g, m => m * 2);

15. Examples

Pipeline transformation

"   aDiTyA   "
  .trim()
  .toLowerCase()
  .replaceAll("a","@")
  .padStart(10,"_");

Manual slice

function sub(s,a,b){
  let r="";
  for(let i=a;i<b;i++) r+=s[i];
  return r;
}

16. ASCII Table

(Your included image remains valid.)


17. Interview Questions

  1. Why are JavaScript strings immutable?
  2. Why does "๐Ÿ˜€".length === 2?
  3. Difference: slice, substring, substr.
  4. Difference: charCodeAt vs codePointAt.
  5. Why avoid new String()?
  6. What does localeCompare provide?
  7. How does matchAll differ from match?
  8. How does JS encode strings internally?
  9. What are surrogate pairs?
  10. How do you correctly count user-visible characters? (Intl.Segmenter)

If you want, I can also export this as PDF, Markdown file, Notion-friendly format, or interview cheat sheet.