<!-- https://learnsql.cpetoday.com/functions/dax/replace -->
# REPLACE

Language: DAX
Category: Text
Syntax: REPLACE(<old_text>, <start_num>, <num_chars>, <new_text>)
Summary: Replaces part of a text value, starting at a position and covering a set number of characters.
Returns: Text (a scalar).
Level: Intermediate
Related: SUBSTITUTE, MID, LEFT, RIGHT, LEN, FIND

## What it does
REPLACE overwrites part of a text value by position. You say where to start, how many characters to cover, and what to put there. This differs from SUBSTITUTE, which finds the text by content. REPLACE is the right tool for fixed-width codes, such as masking the first digits of an account number or swapping one segment of a code.

## Syntax and arguments
- old_text: the value to change.
- start_num: the position of the first character to replace. The first character is 1.
- num_chars: how many characters to replace, starting at that position.
- new_text: the text to put in place of those characters. It may be shorter or longer than num_chars.

## Example
Vendor bank account numbers are shown on screens for review, but the first eight digits must be hidden.

```dax
Masked Account =
REPLACE(Vendors[BankAccount], 1, 8, "********")
```

A number of twelve digits shows the last four in full and the first eight as asterisks. This is a display mask, so restrict the screens that show it, and do not treat it as a security control.

## Example: a second, different use
Change the year segment of a fixed-format document reference from 2025 to 2026 for a rollover:

```dax
New Reference = REPLACE(Documents[Reference], 4, 4, "2026")
```

If the reference is "INV2025-0142", the year at positions 4 to 7 becomes 2026. The rest of the reference is kept unchanged.

## Things to watch
- REPLACE works by position, so a change in the format moves the target. Test it on a sample of rows first.
- Positions start at 1. A start of 0 is an error or an unexpected result.
- If new_text is longer or shorter than num_chars, the text grows or shrinks. The rest of the text moves.
- To remove a word wherever it appears, use SUBSTITUTE. REPLACE is for known positions.
- REPLACE returns text. Do not use it on a value you need as a number.

## In business terms
REPLACE is used for masking account numbers on screens, rolling fixed-format references to a new year and cleaning codes with a known layout. Auditors ask for masking when personal or bank data appears on review screens, so a clear rule is useful.
