---
title: "replace()"
description: "Replaces all substrings of a string that match a regular expression with a replacement string."
date: 2026-04-18T00:00:00Z
version: "2.0"
versionLabel: "XSLT 2.0"
category: "string function"
syntax: "replace(string, pattern, replacement, flags?)"
tags: ["xslt", "reference", "xslt2", "xpath"]
---
## Description
`replace()` searches the input string for all occurrences of the regular expression `pattern` and substitutes each match with the `replacement` string. Unlike `translate()` (which works character-by-character), `replace()` operates on substrings and patterns, making it suitable for complex string transformations.
The `replacement` string may include **back-references** to captured groups using `$1`, `$2`, etc., where `$0` refers to the entire matched substring. Dollar signs that are not back-references must be escaped as `\$`.
The function uses XPath regex syntax (a subset of XML Schema regex), which is similar to Java/Perl regex but does not support lookaheads or backreferences in the pattern itself.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `string` | xs:string | Yes | The input string to perform replacements on. |
| `pattern` | xs:string | Yes | Regular expression pattern matching the substrings to replace. |
| `replacement` | xs:string | Yes | Replacement string; may use `$0`, `$1`, etc. for captured groups. |
| `flags` | xs:string | No | Regex flags: `i` (case-insensitive), `m` (multiline), `s` (dot-all), `x` (extended). |
## Return value
`xs:string` — the input string with all matches of `pattern` replaced by `replacement`.
## Examples
### Remove unwanted characters
**Input XML:**
```xml
$1,299.00
$849.50
```
**Stylesheet:**
```xml
```
**Output:**
```xml
1299.00
849.50
```
### Reformat a date using back-references
**Input XML:**
```xml
Conference
Workshop
```
**Stylesheet:**
```xml
```
**Output:**
```xml
Conference
Workshop
```
*Note: curly braces inside attribute value templates must be doubled: `{{` and `}}`.*
### Collapse multiple spaces
```xml
```
## Notes
- `replace()` replaces **all** occurrences, not just the first. There is no `replaceFirst()` equivalent in XPath.
- To escape a literal `$` in the replacement string, write `\$`.
- The pattern cannot match an empty string; if the pattern can match zero characters Saxon raises a dynamic error.
- For simple character substitution, `translate()` (XSLT 1.0) is simpler and more efficient. Use `replace()` when you need pattern matching or back-references.
- Inside attribute value templates, curly braces within the regex (e.g., `\d{4}`) must be doubled: `\d{{4}}`.
## See also
- [matches()](../xpath-matches)
- [tokenize()](../xpath-tokenize)