Sub topic 6
Cleaning text: trim, clean, case, and replace
Text columns cause many quiet data problems. "Alice Smith", "alice smith " and "ALICE SMITH" look the same to a person, but Power BI treats them as three different values. This chapter covers the four text transformations that fix most of these problems, and the edge cases where they don't.
This chapter assumes you can open the Power Query Editor, read the Applied Steps pane, and set a column to the Text data type. You should also know that each step appears as a line of M code in the formula bar.
Why text values differ when they look the same
Several kinds of difference hide in text:
- Extra spaces at the start or end of a value.
- Non-printing characters such as line feeds and tabs, often from copied web or Excel text.
- Different capitalization of the same word.
- Placeholder strings such as "N/A", "none", or "-" that mean "missing".
- Special spaces, such as the non-breaking space (character code 160), which look like a normal space but are a different character.
A visual that groups by Customer shows a separate row for each variant. A relationship between two tables fails to match "West" with "West ". Relationships and grouping in the model compare values exactly, so clean the text before loading.
The four main transformations
All four are in the Transform tab, under Format (trim, clean, and case) and Replace Values. Select one or more text columns first.
| Transformation | M function | What it does | What it leaves alone |
|---|---|---|---|
| Trim | `Text.Trim` | Removes leading and trailing whitespace | Spaces between words |
| Clean | `Text.Clean` | Removes control characters such as line feeds and tabs | Normal spaces and non-breaking spaces |
| Lowercase / UPPERCASE | `Text.Lower`, `Text.Upper` | Changes every letter | Digits and symbols |
| Capitalize Each Word | `Text.Proper` | Uppercases the first letter of each word and lowercases the rest | Nothing: it rewrites existing capitals |
| Replace Values | `Table.ReplaceValue` | Swaps one value or substring for another | Values that don't match exactly, including case |
Trim and Clean work on different problems
Trim only touches the ends of a value. It does not collapse "New York" (two spaces) into "New York". Clean removes control characters anywhere in the value, but it does not remove ordinary spaces. Use both, usually Clean first and then Trim. Removing a line feed can leave a space at the end that Trim then removes.
Choosing a case
Pick one case for columns you group or join on. Lowercase or UPPERCASE is the safest for join keys, such as email addresses or product codes. Capitalize Each Word suits display names, but it has limits. It turns "McDonald" into "Mcdonald" and "USA" into "Usa". Apply it only to columns where those cases are rare, or fix the exceptions afterward with Replace Values.
A worked example
This query builds a small table with the problems above. The M escape #(00A0) is a non-breaking space and #(lf) is a line feed.
let
Source = #table(
{"Customer", "City", "Status"},
{
{" alice smith ", "New#(00A0)York", "N/A"},
{"BOB#(lf) JONES", "new york", "n/a"},
{"carol lee", "NEW YORK", "Active"}
}
),
FixedSpecialSpace = Table.ReplaceValue(Source, "#(00A0)", " ", Replacer.ReplaceText, {"City"}),
CleanedText = Table.TransformColumns(
FixedSpecialSpace,
{
{"Customer", each Text.Proper(Text.Trim(Text.Clean(_))), type text},
{"City", each Text.Proper(Text.Trim(Text.Clean(_))), type text},
{"Status", each Text.Lower(Text.Trim(_)), type text}
}
),
ReplacedPlaceholder = Table.ReplaceValue(CleanedText, "n/a", null, Replacer.ReplaceValue, {"Status"})
in
ReplacedPlaceholderAfter this query runs:
- Customer holds "Alice Smith", "Bob Jones" and "Carol Lee".
- City holds "New York" in all three rows. Without the special-space replacement, the first row would stay different from the others.
- Status holds
nullfor the first two rows and "active" for the third.
The editor's own steps nest the functions the same way. Selecting the column and choosing Trim, Clean, then Capitalize Each Word creates three steps, each wrapping Table.TransformColumns. The version above merges them into one step per column. This is a reasonable edit when you want fewer steps.
Why the order matters
Placeholders come after case because Replace Values is case-sensitive. If you lowercase first, you only need to match "n/a" once instead of "N/A", "n/a", and "N/a".
Replace Values in detail
Replace Values has two behaviors, and the choice shows up in the M code:
- Whole-value replacement uses
Replacer.ReplaceValue. The cell must equal the search text exactly. This is the default in the dialog. - Substring replacement uses
Replacer.ReplaceText. The search text can appear anywhere in the cell. In the dialog, this is what you get when you leave Match entire cell contents unchecked under Advanced options.
The first approach is safer for placeholders. Replacing "N/A" with whole-value matching leaves "Not N/A-listed" alone, while substring matching would alter it. Use substring replacement for fixing parts of a value, such as turning "St." into "Street".
To replace with a missing value, type nothing in the Replace With box. Power Query writes null. A blank cell and a text value of "" are different things, and later chapters on nulls cover that difference.
Edge cases and common errors
Collapsing repeated internal spaces
Trim leaves "carol lee" unchanged. To collapse runs of spaces, split on the space, drop the empty pieces, and join the rest back together:
let
Source = #table({"Name"}, {{" carol lee "}, {"dan o'neil"}}),
Collapsed = Table.TransformColumns(
Source,
{{"Name", each Text.Combine(List.Select(Text.Split(_, " "), each _ <> ""), " "), type text}}
)
in
CollapsedThis also trims the ends, because splitting " carol" produces empty pieces that the filter removes.
Special spaces that survive Trim and Clean
If a value looks clean but still fails to match another, check its length. Add a custom column with Text.Length([City]) and compare it to what you expect. A mismatch usually means a hidden character. Replace it explicitly, as in the example above, with Character.FromNumber(160) or the #(00A0) escape.
Type errors
Text.Trim and the other text functions expect text. If the column is a number or date, each Text.Trim(_) returns an error for every row. Set the column to Text first, or use Text.From(_) inside the function. Do this only for columns that should be text, such as ZIP codes or product IDs. Converting a real number column to text breaks sorting and math.
Null values
The text functions return null for a null input, so missing values pass through without errors. Trimming does not turn an empty string into null. If a column has both, replace "" with null as a separate step.
Case sensitivity in other steps
Replace Values, Remove Duplicates, and filters all compare text case-sensitively. If "West" and "WEST" should count as the same, change the case before those steps. Otherwise Remove Duplicates keeps both rows.
Checking your work
After cleaning, switch on Column distribution under View and compare the distinct count with what you expect. Removing trailing spaces and unifying case should reduce the distinct count of columns like City or Region. If it does not drop, a different character is probably involved, so use the length check above.
Exercise
A Region column has the values "West", "west ", "WEST", and "West" followed by a non-breaking space. You apply Text.Trim and Text.Lower to the column, but the Column distribution shows two distinct values instead of one. What is the most likely cause, and which step fixes it?
Show answer
The non-breaking space (character code 160) is still attached to one value, and Trim does not reliably remove it. Add a Replace Values step that replaces #(00A0) (Character.FromNumber(160)) with a normal space or an empty string, using Replacer.ReplaceText so it matches inside the value. Run it before Trim, then apply Trim and Lower again. The distinct count should drop to one.
Exercise
You run Replace Values to change "N/A" to null in a Status column. Rows containing "n/a" and "N/A " are still there afterward. Give two ways to fix this.
Show answer
Replace Values matches exactly and is case-sensitive, so "n/a" and "N/A " (with a trailing space) don't match "N/A". First option: apply Text.Trim and Text.Lower to the column, then replace "n/a" with null. Second option: add one Replace Values step per variant. The first option is better because it also handles variants you haven't noticed yet.