String Manipulation
& Regex
Master JavaScript's built-in string methods: split, join, trim, replace, and unlock the power of regular expressions for pattern matching.
Strings: Your Building Blocks of Text
A string is a sequence of characters wrapped in quotes. In JavaScript, strings are immutable: every method returns a new string rather than changing the original.
Why String Methods Matter
Almost every real-world program works with text: parsing user input, formatting output, cleaning data, or searching for patterns. JavaScript gives you a rich toolkit of string methods to handle all of this.
The Core Four: split, join, trim, replace
.split(): String to Array
split(separator) divides a string at each occurrence of the separator and returns an array of substrings.
.join(): Array to String
join(glue) is the inverse of split: it combines array elements into a single string, inserting the glue between each element.
.trim() & .replace()
split vs replace: When to Use Which
| split + join | replace / replaceAll | |
|---|---|---|
| Returns | Array, then String | String directly |
| Best for | Restructuring (change delimiter) | Swapping content in place |
| All occurrences? | Always (by nature) | Only with replaceAll or /g flag |
| Example use | CSV to TSV | Censor a word |
Enter Regular Expressions
A regular expression (regex) is a pattern used to match character combinations in strings. In JavaScript, regex is written between forward slashes.
Regex Building Blocks
Regex Flags
Flags go after the closing slash and change how the regex engine searches.
How to Apply These Tools
.trim().split(" ").join("-")Example 1: Clean & Reformat a Name
Task: convert " jane DOE " into "Jane Doe".
Example 2: Regex Replace for Masking
Task: replace every digit in a credit card number with "*".
Example 3: Validate an Email Pattern
Task: check if a string looks like a valid email address.
Common Mistakes
.replace("a","b") and expecting all "a"s to change. Without \(\texttt{g}\), only the first match is replaced.str.trim() changes str. It does not: you must assign the result: str = str.trim().Method Summary Table
| Method | Input | Output | Key Use |
|---|---|---|---|
| .split(sep) | String | Array | Break apart |
| .join(glue) | Array | String | Reassemble |
| .trim() | String | String | Clean whitespace |
| .replace() | String | String | Swap first match |
| .replaceAll() | String | String | Swap all matches |
| /regex/.test() | String | Boolean | Pattern check |
| .match(regex) | String | Array/null | Extract matches |
Question 1 of 5
What does "a,b,c".split(",") return?
["a", "b", "c"].Question 2 of 5
What does " hello ".trim() return?
Question 3 of 5
What does "foo bar foo".replace("foo", "x") return?
Question 4 of 5
Which regex matches one or more digits?
Question 5 of 5
What does ["red","green","blue"].join(" - ") return?