Text transformation
Normalize or transform user input without altering the original value.
JS Puzzles · Const
JavaScript strings are immutable: once created, their contents cannot be changed. String operations return new strings, so retain the result when you need transformed text.
A JavaScript string cannot be changed after it is created. Operations that appear to edit text instead produce another string, which you can store by assigning the returned value to a variable; the variable itself may still be reassigned.
const result = string.method(...args);String operations that transform or combine text return a new string; the original remains unchanged.
const original = "hello";
const changed = original.replace("h", "H");
console.log(original); // "hello"
console.log(changed); // "Hello"replace() returns a new string, so the original value remains unchanged.
Normalize or transform user input without altering the original value.
Build labels, messages, or paths from existing string values.
Preserve an original value while producing an edited variant.
Strings are immutable primitive values, so their contents cannot be modified in place. Methods such as replace() return a new string rather than changing the receiver.
Follow-up: What happens if a variable holds a string? The variable can be reassigned to the newly returned string, but the original string value is still unchanged.
An assignment such as str[0] = "H" cannot replace the first character of a string. To change the text, construct a new string and assign that new value to the variable.
Follow-up: How would you replace every occurrence? Use replaceAll(), or use replace() with a global regular expression.
String transformation methods return new strings because primitive values are immutable. Therefore, code must capture the return value when it needs the transformed text.
Follow-up: Does const make the string immutable? No: the string value is immutable independently; const only prevents rebinding that particular variable.
StringString.prototype.replace()String.prototype.replaceAll()String.prototype.concat()String.prototype.substring()Primitive