Strings in JavaScript are immutable primitives. Methods like str.toUpperCase() and str.replace() return a brand-new string without modifying the original. You must reassign the result.
Trap #2: str.replace() vs str.replaceAll() Single Match Trap
Calling "a-b-c".replace("-", ":") replaces only the FIRST hyphen, producing "a:b-c". Use str.replaceAll("-", ":") or a global regular expression /-/g.
Trap #3: Unicode Surrogate Pairs and Emoji Length
JavaScript strings are UTF-16 code units. An emoji like "👍".length evaluates to 2, and complex emojis can have a length of 7+. Use [..."👍"].length to count perceived characters accurately.
Multi-line template literals preserve all leading indentation tabs and spaces as literal characters, which can break formatted text and terminal messages.
Trap #5: Lexicographic String Sorting Mismatch
Comparing strings with > or < uses ASCII/UTF-16 code point values, meaning "Z" < "a" evaluates to true. Use strA.localeCompare(strB) for natural language sorting.
💬 Frequently Asked Questions
What is the difference between single quotes, double quotes, and backticks?
Single and double quotes are interchangeable for string literals. Backticks define template literals that support multi-line text, expression interpolation with ${expr}, and tagged template functions.
How do you check if a string contains a substring in modern JavaScript?
Use str.includes(substring), which returns true or false, replacing the legacy str.indexOf(substring) !== -1 idiom.
What does str.padStart() do?
padStart(targetLength, padString) pads the current string from the start with a given string until the resulting string reaches the target length (e.g. formatting numbers as 001).
How does str.trim() handle whitespace?
trim() removes spaces, tabs, and all newline characters from both ends of a string. trimStart() and trimEnd() trim individual ends.
Why should you avoid using eval() to parse stringified expressions?
eval() executes strings as arbitrary JavaScript with full access to the lexical scope, opening catastrophic Cross-Site Scripting (XSS) and code injection vulnerabilities.