3.7 SUBSTITUTE, REPLACE, TRIM, CLEAN and Case Functions
Clean a label while keeping its meaning
A fictional seller preparing an Amazon product worksheet receives one label as Greenvale Cow Milk with extra spaces, another with an invisible word break, and a third with a brand that has intentional capital letters. The owner wants consistent report labels. The raw values should remain available so a teammate can see what was actually imported.
These source records, product labels and store conventions are invented for practice. The example describes no real catalog rules or import process at Amazon, Blinkit or Swiggy. Begin with the question “Which characters are allowed to change?” That determines whether you should replace literal text, change characters at a known position, clean stray controls, or adjust case for a display field.
Inspect a space before trying to remove it
Plain spaces, nonbreaking spaces, tabs and line breaks can all create separation that looks similar on a spreadsheet. A nonbreaking space is a character used to keep text pieces together on the same line in some displays. A tab or line feed is a control character that influences layout. In an imported cell these characters remain part of its value even when you do not see a distinct symbol.
TRIM handles the ordinary space
=TRIM(A2) removes ordinary leading and trailing spaces and reduces repeated ordinary spaces between words to one. It operates on character 32. In a report name with unwanted padding, this helps make the presentation consistent. If exact spacing is part of the field's specification, such as a fixed-width text import, keep that formatting in the raw source and only trim a derived display value when appropriate.
CLEAN handles a specified range of older controls
=CLEAN(A2) removes the first 32 ASCII control values, zero through 31. Tabs, line feeds and carriage returns fall in that set. CLEAN does not remove every invisible Unicode character. It also deletes a removed character instead of replacing it with a space. If an internal line break is the only separator between words, cleaning first can join them accidentally.
Use the specific character when the space is nonbreaking
UNICHAR(160) supplies a nonbreaking space using its Unicode number. On a real source where you can identify that character, =SUBSTITUTE(A2,UNICHAR(160)," ") changes it to an ordinary space. You can then use TRIM to handle the surrounding space consistently. Microsoft identifies other nonprinting characters beyond the ASCII controls. Identify and handle those explicitly when they occur in the actual source.
A code point is a number that identifies a character under Unicode. To inspect the fifth character of a suspect label, first use =MID(A2,5,1) to isolate it, then pass that result to UNICODE. An ordinary space gives 32 and a nonbreaking space gives 160. A length check alone cannot tell the two apart, since both can contribute one character in these examples.
Choose between matching text and replacing a position
SUBSTITUTE follows the exact characters
=SUBSTITUTE(A2,"OLD","NEW") looks for literal OLD inside A2 and replaces each occurrence. With BAG-OLD-OLD as input, it returns BAG-NEW-NEW. You can supply the optional occurrence number to change a particular match. Add 2 as the fourth argument to change the second occurrence only, producing BAG-OLD-NEW.
The match is case-sensitive. If the source contains lowercase old, an uppercase OLD pattern does not match those letters. It also matches a substring without requiring it to be a whole word. Replacing "Old" can change OldTown as well as an isolated Old label. Use an exact field or a matched delimiter when only a named part should change. Test a word that should remain intact.
REPLACE follows an address within the text
=REPLACE(A2,1,6,"XXXXXX") starts at the first character, replaces six characters and inserts six X characters. If A2 is the fictional ten-character string 0000002718, the result is XXXXXX2718. You would choose this when the desired part has a known position. REPLACE does not need to know what the original six characters were.
The length you remove and the length you insert can be different. For example, =REPLACE("ABCD",2,2,"-") returns A-D. It removes B and C starting at position two and inserts one hyphen. This is useful for a documented abbreviation or punctuation change. Check the new length if another formula expects the original width.
Lab 1 · Build a repeatable product-label cleanup
Create a scratch worksheet named Labels. Use columns A Raw label, B Word boundaries, C Other controls removed, D Trimmed label and E Display test. For the raw rows below, type the formulas exactly so you can reproduce ordinary spaces, invisible characters and capitalization without relying on copy and paste.
| Row | Source expression | Expected trimmed label |
|---|---|---|
| 2 | =REPT(" ",2)&"greenvale cow milk"&REPT(" ",3)&"500 ML"&REPT(" ",2) | greenvale cow milk 500 ML |
| 3 | ="Fresh"&UNICHAR(160)&"Curd"&REPT(" ",3)&"400 G" | Fresh Curd 400 G |
| 4 | ="Red"&CHAR(10)&"Lentils 1 KG" | Red Lentils 1 KG |
| 5 | ="USB"&CHAR(9)&"Cable" | USB Cable |
| 6 | =REPT(" ",2)&"iPhone case"&REPT(" ",3)&"navy " | iPhone case navy |
Replace separators before removing residual controls
- Check
=UNICODE(MID(A3,6,1))in an empty cell. The sixth character follows Fresh. It should return 160. This is direct evidence of the type of space between the words. The string already has a visible separation, so LEN alone cannot identify its cause. - In B2, replace each documented separator with an ordinary space. For this exercise the source labels use nonbreaking spaces, line feeds, tabs and possibly carriage returns between words. A user could inspect each transformation in a separate helper first, then use the combined expression below.
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,UNICHAR(160)," "),CHAR(10)," "),CHAR(9)," "),CHAR(13)," ")
- Fill B2 down through B6. Verify
=UNICODE(MID(B3,6,1))now returns 32. Compare B4 and B5 with the source. Red is now separated from Lentils by a normal space, and USB is separated from Cable the same way. - In C2 enter
=CLEAN(B2)and fill it down. This removes any remaining ASCII controls covered by CLEAN. The inserted ordinary spaces should stay. In this simple fixture every control had already been accounted for by B. Leave C as a separate stage so its behavior is clear when another source has residual padding controls. - In D2 enter
=TRIM(C2)and fill it down. Compare each row with the table. D2 should have a single space before 500 ML and no outer padding. D3 should keep each word distinct. D5 should read USB Cable with its original uppercase abbreviation. - Try
=CLEAN(A4)separately. It returns RedLentils 1 KG because it removes the line feed. This is the experiment that justifies the order of operations. The same CLEAN step applied to B4 preserves the replacement space.
Track the fourth row through the label cleanup
Read the raw boundary
A4 contains Red, a line feed, and Lentils 1 KG. The line feed is the only separator between the first two words.
Preserve the separation
The substitution turns that line feed into one ordinary space. Both words remain intact.
Remove other controls and padding
CLEAN and TRIM now process the substituted result. The ordinary space between Red and Lentils remains one character.
Compare with the approved label
The trimmed label is Red Lentils 1 KG. The original row is still available so a reviewer can see why the word boundary was preserved.
Test capitalization in a field meant for display
In E2 try =PROPER(D2), then fill through E6. E2 reads Greenvale Cow Milk 500 Ml. E5 reads Usb Cable. E6 reads Iphone Case Navy. The case function uses general capitalization rules and does not know brand spellings or unit conventions. A human-approved display field can require exceptions or the source spelling for those rows.
For the first row only, suppose the fictional style guide calls for a lowercase ml suffix. If E2 ends in the exact three-character text " Ml", use =REPLACE(E2,LEN(E2)-1,2,"ml") in another column. It starts at the second-to-last character and replaces the last two. The resulting display is Greenvale Cow Milk 500 ml. A general formula should check that suffix first, so it does not rewrite unexpected names.
Lab 2 · Change a known code segment and build a masked field
Start a scratch sheet named Codes. These changes have two different goals. The first replaces a known substring in a product identifier. The second replaces fixed positions in a separate sample string to produce a presentation field. Use only the synthetic codes below.
Replace a specified occurrence
- In A2 type
BAG-OLD-OLD. In B2 use=SUBSTITUTE(A2,"OLD","NEW"). It gives BAG-NEW-NEW. Both exact occurrences were found. - In C2 use
=SUBSTITUTE(A2,"OLD","NEW",2). It gives BAG-OLD-NEW. The second OLD begins after the second hyphen, which verifies that instance number chooses an occurrence of the text. - Temporarily change A2 to
BAG-OLD-old. B2 updates to BAG-NEW-old. C2 now leaves the source unchanged because there is no second uppercase occurrence. A formula can leave the value exactly as supplied without giving an error. Compare the intended result with the original when you expect a specific replacement to happen. - Restore A2. In A3 enter
ORD-101-101, a made-up order migration code. Use=SUBSTITUTE(A3,"101","202",1)to update the first literal identifier part. Try=REPLACE(A3,5,3,"202")in another cell. Both give ORD-202-101 for this exact layout. The first formula is about the old field content, and the second is about positions five through seven. - Change A3 to
ORDX-101-101. The positional formula would now begin at the hyphen and overwrite the wrong segment, giving ORDX2021-101. The substitute formula still finds the first exact 101 and gives ORDX-202-101. Restore the original code. This shows why positional cleanup should be used only when the source shape permits it.
Make a separate masked presentation
In A5 enter '0000002718. The leading apostrophe tells Excel to store the following digits as text, so they keep the original width. The apostrophe is an entry instruction. The string being passed to the text formula has ten characters. This is a synthetic placeholder, not a real contact number.
- In B5 enter
=LEN(A5). Expect ten. If a paste has already converted the input to 2718, the length and raw representation changed. Fix the input field type before applying position-based masking. - In C5 enter
=REPLACE(A5,1,6,"XXXXXX"). Expect XXXXXX2718. Compare its final four characters with=RIGHT(A5,4). The two suffixes should be identical. - Try a short source such as
'02718in a separate row. A formula designed to replace the first six positions cannot yield the same safe ten-character display. Use a length condition so it displays Check length when the source format fails. Check other required features, including expected type and digits, before using a masking rule on a real dataset. - Test a formatted sample like
000-000-2718. It follows a different layout. Either design a rule documented for that exact shape or keep it in a review group. A direct position update for the ten-digit fixture would handle the punctuation at unintended positions.
The masked column is a presentation field. A workbook that still contains the original raw column still contains the original data. If a report should never disclose that column, publish a separate values-only report that contains only the approved fields, and inspect it before sharing. Hiding a worksheet or column leaves its data in the workbook.
Choose capitalization for a particular field
UPPER makes letters uppercase. It can be useful for a practice status taxonomy that uses DELIVERED and CANCELLED as approved labels. LOWER makes letters lowercase. It can help produce a matching key when the source owner confirms the text comparison is case-insensitive. PROPER applies a general title-like pattern to the text by capitalizing letters at word starts, including after non-letter characters, and lowercasing other letters. Check the result on names and abbreviations before presenting it.
Respect the source's meaningful capitalization
- A product display such as USB Cable uses an abbreviation. A PROPER result can read Usb Cable. Use the approved display label on records with intentional capitalization.
- A case-sensitive SKU or token might treat uppercase and lowercase identifiers as different. An indiscriminate UPPER rule can map both to the same result. Preserve the original key and test the documented rule.
- Keep case formatting separate from search when retrieval and display have different requirements. A normalized matching field can use uppercase while a display field keeps brand spelling such as iPhone.
- Use EXACT to verify case when the policy requires it. A normal visual comparison can miss a single uppercase letter in a string. A checked reference label lets you test the intended result reliably.
For a study exercise on a Swiggy-inspired order report, treat delivered, Delivered and DELIVERED as the same conceptual state, by explicit classroom policy. UPPER after whitespace cleaning yields one stored label. On an identification column, do not replay that procedure automatically. A display label and an identifier can have different requirements in the same workbook.
Notice when distinct raw inputs produce the same result
Normalization means applying a consistent representation before comparing values. Sometimes several distinct raw spellings should map to one normalized result. Other times that would lose an important distinction. You can detect the collision by placing the raw and derived key side by side and counting how often each derived value appears.
Predict an intended grouping
Enter these four fictional status labels on a scratch tab: delivered, Delivered followed by one ordinary space, DELIVERED, and Cancelled. Apply UPPER after TRIM to each. The first three now share DELIVERED and the last becomes CANCELLED. A COUNTIF on the derived field should show three delivered and one cancelled. The group was intentional.
Predict an accidental collision
Enter two separate test identifiers Sku-07 and SKU-07. In the exercise, the source treats them as different identifiers. If you uppercase both, the outputs become indistinguishable. EXACT on the source pair is FALSE, and EXACT on the uppercase pair is TRUE. That result shows why blindly applying the same transformation to fields with different meanings can cause duplicate-looking keys.
Before grouping a report by a derived key, check whether more than one originally distinct product or account now shares it. Have the owner of the actual source confirm the group definition. Keep the old labels available so a later reader can explain which records were grouped and recreate the result.
Inspect an invisible character with a tiny diagnostic table
Suppose two area names look like Pune East on the sheet. One row uses a plain space between the words. Another uses a nonbreaking space that came from a web page. The words and the length can be identical while an exact comparison still reports FALSE. Identify the actual code point before adding another transformation to the whole import.
Give the invisible characters a readable value
- In an unused area, make one sample with
="Pune East"and another with="Pune"&UNICHAR(160)&"East". Name the two cells in adjacent labels so you remember the input each one represents. - Use LEN to measure both. Each gives nine. Find the separator position by counting four letters in Pune and then one boundary character. Use MID at position five to extract just the separator in a helper.
- Use UNICODE on each extracted character. The plain space gives 32 and the nonbreaking space gives 160. Use an exact comparison to confirm the original examples did differ as stored.
- Run the replacement for code point 160 followed by TRIM. The expected output for both is the same ordinary-space label. Compare the results with EXACT and expect TRUE. The new function solves the observed cause, rather than deleting every unfamiliar character.
Now make the same second sample with UNICHAR(8239). This is a narrow no-break space, another code point. The substitution for 160 leaves that new character in place. If the confirmed import uses both characters to separate words, document and test a separate replacement for 8239. Keep the rule limited to the field and accepted meaning.
Put transformations in the order that keeps boundaries visible
When a cleanup expression contains several nested functions, the inner step runs before the outer step. A label that arrives as Red, a line feed and Lentils must still have a boundary when you reach TRIM. A formula applying CLEAN before the known boundary replacement deletes the separator. A later substitution cannot replace a character that is already gone.
Test a Windows-style pair made with ="Red"&CHAR(13)&CHAR(10)&"Lentils" on a scratch row. The carriage return and line feed are two characters. Replacing each with one ordinary space temporarily creates two spaces between the words. TRIM collapses them and gives Red Lentils. With source paragraphs or notes, you might need to keep the multiline structure. This replacement order is for a single-line label field.
Check each stage on a variety of sources
- A conforming row. A label that already reads USB Cable should stay unchanged when whitespace treatment is the goal. This helps prove that the rule avoids unnecessary edits to valid values.
- A known boundary. A tab between USB and Cable should become a space if the export uses it to separate words inside this label. Deleting the tab would give USBCable, a different label.
- A known invalid residual. If a stray control character occurs next to ordinary padding, cleaning it after handling boundaries can remove the noise without joining the words. A raw copy keeps the strange input visible for future inspection.
- A meaningful exception. A brand display or acronym might need one uppercase string even though most ordinary labels use a title-like appearance. Place those approved cases in a separate reference list rather than changing the whole source to suit one exception.
For the whitespace rule, use a repeatable check: clean the derived label once more and see whether it changes. A well-defined whitespace normalization in this exercise yields the same result on the second pass. Compare prepared output with an independently written clean label to verify more than the repeated pass. A rule that always deletes the whole cell could also stop changing, so repeatability does not by itself prove correctness.
Apply code and label changes where the whole field matches
Consider a fictional supply report that is migrating an old store label to a current display label. The source contains both North Old and North Old Warehouse. A SUBSTITUTE formula targeting just Old would change both. The report owner meant to update only the exact store label North Old. A whole-field comparison gives you a way to state that limited decision.
- Put
North Oldin A2 andNorth Old Warehousein A3. A broad pattern replacement with the word New yields North New and North New Warehouse. Depending on the source rules, the second edit could be wrong. - Use
=IF(EXACT(A2,"North Old"),"North New",A2)as a simple comparison. Fill it to the next row. The first becomes North New and the second stays North Old Warehouse. Here EXACT uses a whole-field match with case sensitivity. The result depends on preserving the exact approved case and spaces. - If the team accepts alternate capitalization and whitespace, normalize a copy of the relevant field first. Compare against a correspondingly normalized rule. Test a look-alike that should still stay separate. Keep the original spelling in the source column unless the owner approves an actual source change.
- When there are many approved mappings, maintain a small reference table instead of nesting numerous one-off replacements. Put the original key and approved display value on one row. You can later apply an exact lookup and review any unmatched labels. A table gives another person a visible place to update the mapping.
Check when a second replacement would change the first result
Suppose a training file says to map one original code word Old to New and another code word New to Current. A sequential workflow that changes Old to New and then applies the second replacement to that derived value would turn the original Old into Current as well. If the rules are meant to apply to the original source values independently, compare against the unmodified value or use a reference mapping. Test one row for each original code and state the intended output before combining transformations.
This reasoning also helps when cleaning currency and numeric fields. First decide whether the source represents an identifier, a name or an amount. Removing punctuation from the wrong field can merge codes or transform a decimal point with business meaning. Leave measurement conversion to a documented numeric rule after identifying the characters and separators that belong to its source format.
Make cleaned data reviewable by a teammate
Give each derived field a specific role. A raw code, normalized lookup key and readable display label can all exist for one record. Maintaining separate fields makes it possible to rebuild a report when the mapping changes. The user who opens it should be able to find the raw import and read the transformation stages in order.
- Record source and reviewed changes. State which separators the input can include, which case is meaningful, and which masking pattern is only for display. Include one passing row and one review row for every critical rule.
- Make unchanged results visible. A text substitution without a match can return the input untouched. Compare with the source when you expected a migration, and record which labels still need manual resolution.
- Preserve a real blank when the field is unknown. A cleanup may turn a space-only input into empty text. Treat that result as a possible missing measurement rather than inventing a value. Keep an explicit review marker when the outcome should carry a reason.
- Check the output beyond a screenshot. Use LEN and EXACT with independently typed examples. A screenshot can hide trailing blanks and differences in similar characters. Check the result after import or export if the receiving tool may choose a different data type.
When a process owner later asks for another change, start from the preserved raw text and run the whole documented sequence on a scratch copy. Compare the already-known examples before you trust any new result. A cleanup rule should be a visible decision someone else can reproduce.
Check the effect of cleanup on a small summary
Use a four-row status fixture where the label is meant to be case-insensitive and ordinary outer padding is accidental. The exercise describes an invented delivery status group. Enter Delivered, Delivered followed by a trailing ordinary space, Delivered followed by a nonbreaking space, and Cancelled in A2 through A5 on a scratch tab. You can build the last character in each of the two dirty labels with a formula so it stays present during entry.
- Compare each row independently with the approved label. The first record's text is already correct. The other two Delivered-looking values contain additional characters. Use LEN to distinguish nine-letter Delivered from the longer entries.
- In B2 use
=TRIM(SUBSTITUTE(A2,UNICHAR(160)," "))and fill down. Both trailing-space cases become Delivered. The Cancelled label remains Cancelled. Verify the one transformation step involved in each change. - Use
=COUNTIF(B2:B5,"Delivered"). It returns three on the normalized field. COUNTIF already compares ordinary letter case insensitively. The whitespace correction is what lets these three labels reach the intended stored text. - Check the source and result groups side by side. The four records should still exist. No amount or time field should change. Each record is given one cleaned label. A normalized group can become larger even when the underlying number of orders remains the same.
Now add a row that contains only ordinary spaces. The derived TRIM returns empty text. Do not interpret its empty-looking appearance as a missing physical cell in the formula column. It still holds a formula, and some counting functions classify that differently. If the status needs attention, give it a separate review category and let the source owner supply the intended state.
If you later share the normalized field, preserve an explicit distinction between unknown statuses and known cancellations. A blank might represent recently imported records awaiting a source update. Assigning those rows to Cancelled would change the cancellation count and meaning of a reported rate, even if the workbook no longer looked messy.
Decide whether internal spaces belong to an identifier
Try the practice codes ABC 10 and ABC1 0. The exercise owner says a space separates two meaningful parts. TRIM leaves the two codes distinct. Replacing every space with empty text would produce ABC10 for both. The operation removes clutter only if the source really says those boundaries have no meaning. Before recommending an empty replacement, ask what a downstream formula or source viewer might need to recover from the code.
Check an outer-padding example separately. Prepend two ordinary spaces to ABC 10 and append one ordinary space. The intended clean output is the original five-character group plus its internal separator, reading ABC 10. Use EXACT to compare it to a separately entered approved code. This makes it possible to prove that the interior separator survived while the padding was removed. Run the same test on ABC1 0 so the two outputs are recognizably distinct.
- Make an expected result column for a few approved cases. Add a separate test for unchanged labels and one case where a deliberate scope check should send the row to review.
- Keep the original characters in the test sheet where another learner can inspect them. For formula-built hidden characters, keep the expression available so the fixture can be reproduced even after saving or copying text.
- Count changed, unchanged and unresolved rows before carrying the derived field into another report. A record can change as expected and still need separate validation because the final string is not an approved domain value.
- Do a second pass on an already-clean label. If your rule keeps stripping or replacing content on each pass, revise the order or the mapping before applying it to future exports.
Quiz · choose the smallest safe transformation
What does TRIM do to repeated ordinary spaces inside a value?
It reduces the run of ordinary spaces to one, and removes ordinary spaces at the beginning and end. Use the function on a field where extra spacing is accidental. Preserve intentional layout in the raw field.
Why can CLEAN change a line break between Red and Lentils into RedLentils?
CLEAN deletes the line-feed control. It does not insert a space in its place. Substitute a regular space before CLEAN if that boundary should continue to separate the words.
Which approach can distinguish a plain space from a nonbreaking one?
Use MID to inspect the character at the expected position, and UNICODE to show its number. Both may contribute the same length. A plain space has code point 32, and a nonbreaking space has code point 160.
What does SUBSTITUTE with instance 2 return for BAG-OLD-OLD?
With uppercase OLD replaced by NEW, it returns BAG-OLD-NEW. Only the second matched occurrence changes. Removing the instance argument would change every matching OLD.
Why could PROPER be wrong for USB Cable?
It uses a general capitalization pattern and can return Usb Cable. That may break an abbreviation or brand convention. Use an approved display spelling or keep the known exception.
Does a masked column remove the original data from the workbook?
The original data remains in any raw column the workbook contains. Create a separate approved export when the audience should see only the masked values, and inspect the resulting fields before sharing.
Interview practice · explain the transformation order
When would you use SUBSTITUTE instead of REPLACE?
I would choose SUBSTITUTE when I can identify the exact text to replace, such as the second OLD code word. I would choose REPLACE when the instruction specifies a fixed position and length, such as masking the first six characters in a checked ten-character practice field.
Why did a cleaned city label still fail to match the expected value?
I would compare the lengths and inspect suspect characters with UNICODE. TRIM handles ordinary spaces. A nonbreaking space can remain unless the rule replaces it explicitly. I would test the change on one confirmed sample before applying it more widely.
How would you make sure cleanup does not merge different identifiers?
I would keep raw identifiers next to normalized results and check for different original keys that now produce the same value. If capitalization is meaningful to the source, uppercasing two distinct codes could merge them. That field needs a different policy from a report label.
When could you keep a newline rather than cleaning it?
I would keep it in a notes or address field when line structure belongs to the intended value. For a single-line label where the newline separates words, I would replace it with a normal space. I would document which column the rule applies to.
How do you prove that a targeted replacement only changed an approved field?
I would test a known intended match and a nearby string that shares part of the text. If the second string must stay unchanged, use the whole field or an approved mapping rather than an unrestricted substring replacement. Keep the original text so the differences remain auditable.
Six cards for a clean import
- TRIM Remove outer ordinary spaces and reduce repeated internal ordinary spaces. Check for different Unicode spaces separately.
- CLEAN Remove supported ASCII controls. Replace any that form meaningful boundaries before using it.
- SUBSTITUTE Choose the literal text to replace. Optionally name the occurrence you want.
- REPLACE Give a starting position and length to replace. Verify the source shape and resulting width.
- Case Choose UPPER, LOWER or PROPER according to the role of the field. Preserve intentional identity and spelling.
- Source check Keep the raw text available and test expected changes and expected exceptions side by side.
Continue with joining prepared values into a report label. Revisit text positions and character counts if you need a helper to inspect an unexpected source character.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.