REPLACE: By Position, Not by Content
About this lesson
REPLACE swaps a run of characters, chosen by starting position and length, for new text. It does not care what those characters are. A length of zero turns it into an insert.
- replace characters by position with REPLACE.
- insert text into a cell with a count of zero.
- choose between REPLACE and SUBSTITUTE from the data.
The idea
SUBSTITUTE, from the building module, finds text and changes it. REPLACE counts to a position and changes whatever is there. That makes REPLACE the tool for fixed layouts. A year that always sits in characters 5 to 8, or a card number whose first twelve digits are masked. It is the wrong tool for anything whose shape varies.
The trick to remember is a count of zero. REPLACE(G2,3,0,"-") removes nothing and inserts a hyphen at position 3. That is the only way to insert into text without joining two pieces with an ampersand.
The mistake to watch for
Using REPLACE on text whose shape varies. It counts to a position and changes whatever is there. So a code that is one character longer than the others has the wrong part replaced, without any error. REPLACE is for fixed layouts. When you know what the text says, not where it sits, use SUBSTITUTE.
Read more about this
Where this comes up again
This lesson needs JavaScript to run. Everything below is the lesson in full, but you cannot type into the grid or be marked.
REPLACE swaps characters by position and length.
In B2, type:
=REPLACE(A2,1,7,"*******")
| Row | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|
| 1 | Phone | Masked | Invoice | Renumbered | Code | With dash | ||
| 2 | 07700900123 | INV-2023-041 | AB1042 | |||||
| 3 | 07700900456 | INV-2023-042 | CD77 | |||||
| 4 | ||||||||
| 5 | ||||||||
| 6 | ||||||||
| 7 | ||||||||
| 8 |
Every step
-
REPLACEswaps characters by position and length. InB2, type:=REPLACE(A2,1,7,"*******"). -
Invoice numbers carry last year. In
E2, replace 4 characters starting at position 5 with 2024. Shape:=REPLACE(cell,start,n,"new"). -
Read
=REPLACE(D3,5,4,"2024")and say what it returns. -
SUBSTITUTEfinds text anywhere, not by position. InE3, swap 2023 for 2024 withSUBSTITUTE. Shape:=SUBSTITUTE(cell,"old","new"). -
In
H2, insert a hyphen after the 2 letters inG2. Shape:=REPLACE(cell,start,0,"new"). Remember: a length of 0 inserts instead of replacing.