Changing Text Beyond Recognition

1. Case Changing

  • "Hello".toUpperCase()"HELLO"
  • "Hello".toLowerCase()"hello"

2. Slicing (slice) — The Best Way

The slice(start, end) method copies a portion of the string from start up to (but not including) end.

let str = "stringify";
alert( str.slice(0, 5) ); // "strin"
alert( str.slice(2) ); // "ringify" (from the 2nd character to the end)
alert( str.slice(-4, -1) ); // "gif" (counting from the end!)

3. Replacement (replace / replaceAll)

alert( "fizz buzz".replace("z", "s") ); // "fisz buzz" (replaces only the first one!)
alert( "fizz buzz".replaceAll("z", "s") ); // "fiss buss" (ES2021 standard)
Important

Immutability: Strings cannot be changed " in place " . Any string method returns a NEW string.

let s = "Hi";
s[0] = "h"; // Won't work!
s = "h" + s.slice(1); // CORRECT.
Tip

If you need to remove trailing/leading spaces (e.g., from a login form), use str.trim().