The Replace function in Power Apps is used to replace a part of a string with another string. This function is particularly useful for modifying text by replacing specified portions of it, such as correcting errors, formatting, or altering content based on conditions.
PowerApps – Replace() function Syntax
Replace(Source, StartPosition, NumberOfCharacters, ReplacementText)
- Source: The text string in which to perform the replacement.
- StartPosition: The position in the text string where the replacement will begin (1-based index).
- NumberOfCharacters: The number of characters to replace.
- ReplacementText: The text that will replace the specified characters.
Notes:
- Indexing: Remember that StartPosition is 1-based, so the first character of the string is at position 1.
- Handling Errors: Ensure that the StartPosition and NumberOfCharacters parameters are within the bounds of the source string to avoid errors.
PowerApps – Replace string with another string
Suppose you have a string "Hello World" and you want to replace "World" with "PowerApps".
- Add a Label Control:
- Insert a Label control.
- Set the Text property of the Label to:
Replace("Hello World", 7, 5, "PowerApps")
This will display "Hello PowerApps", as it replaces "World" (starting at position 7 and spanning 5 characters) with "PowerApps".
Suppose you want to replace part of a user input string.
- Add a Text Input Control:
- Insert a Text Input control named UserInput.
- Set the HintText property to "Enter text".
- Add a Button Control to Perform the Replacement:
- Insert a Button control named ReplaceButton.
- Set the Text property of the Button to "Replace".
- Add a Label Control to Display the Result:
- Insert a Label control.
- Set the Text property of the Label to:
Replace(UserInput.Text, 1, 5, "PowerApps")
When the user enters text and clicks the "Replace" button, the first 5 characters of the input will be replaced with "PowerApps".
PowerApps – Replace string Based on a Condition
Suppose you want to replace all instances of "foo" with "bar" in a string only if "foo" is found.
- Add a Text Input Control:
- Insert a Text Input control named UserInput.
- Set the HintText property to "Enter text".
- Add a Button Control to Perform the Replacement:
- Insert a Button control named ReplaceButton.
- Set the Text property of the Button to "Replace".
- Add a Label Control to Display the Result:
- Insert a Label control.
- Set the Text property of the Label to:
If(
Find("foo", UserInput.Text) > 0,
Replace(UserInput.Text, Find("foo", UserInput.Text), 3, "bar"),
UserInput.Text
)
When the user enters text and clicks the "Replace" button, any instance of "foo" will be replaced with "bar". If "foo" is not found, the text remains unchanged.