Text.ReplaceRange

Text

Replaces a specified number of characters in a text value starting at the given offset with a new text value.

Examples on this page use shared sample tables. View them to understand the input data before reading the examples below.

Syntax

Text.ReplaceRange(text as nullable text, offset as number, count as number, newText as text) as nullable text

Parameters

NameTypeRequiredDescription
texttextYesThe original text value.
offsetnumberYesThe zero-based position at which to begin the replacement.
countnumberYesThe number of characters to remove before inserting newText.
newTexttextYesThe text value to insert in place of the removed characters.

Return Value

textA new text value with the specified range replaced by newText.

Remarks

Text.ReplaceRange removes count characters from text starting at the zero-based offset position, then inserts newText at that same position. This is a single atomic operation: remove then insert. The replacement text does not need to be the same length as the removed portion — the result may be shorter or longer than the original.

If text is null, the function returns null. The count must be a non-negative number; using 0 for count makes this equivalent to Text.Insert.

This is equivalent to: Text.Start(text, offset) & newText & Text.End(text, Text.Length(text) - offset - count)

The key distinction from related functions: - Use Text.Replace to replace all occurrences of a substring value throughout the text - Use Text.ReplaceRange to replace characters at a specific position and length - Use Text.RemoveRange when you want to delete without inserting anything - Use Text.Insert when you want to insert without removing anything

Examples

Example 1: Replace the status prefix in a formatted string

Text.ReplaceRange("OLD-Report-2024", 0, 3, "NEW")
Result
Result
1NEW-Report-2024

Example 2: Fix a separator character at a known position

Text.ReplaceRange("2024/03/15", 4, 1, "-")
Result
Result
12024-03/15

Example 3: Expand: replace a short code with a longer value

Text.ReplaceRange("E001", 0, 1, "EMP")
Result
Result
1EMP001

Example 4: Shrink: replace a longer segment with a shorter one

Text.ReplaceRange("Sales Representative", 6, 14, "Rep")
Result
Result
1Sales Rep

Compatibility

Power BI Desktop Power BI Service Excel Desktop Excel Online Dataflows Fabric Notebooks