Swift example

How to replace all occurrences in a string in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use replacingOccurrences(of:with:) from Foundation: text.replacingOccurrences(of: "cat", with: "dog") returns a new string with every match replaced. Without Foundation, the standard library has text.replacing("cat", with: "dog"). To remove the last character, use String(text.dropLast()), which is safe on an empty string, or text.removeLast() on a var, which crashes when the string is empty.

Swift strings are values: the replace methods hand you a new string and leave the original alone, unless you call a mutating method such as replace(_:with:) or removeLast() on a var. There are two families to pick from. Foundation's replacingOccurrences(of:with:) is the one most answers show, with options for case and regular expressions. The standard library's replacing(_:with:) needs no import and takes regex literals and closures. The sections below cover both, regex replacement, deleting characters, removing the last character, and replacing only the first match, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1replacingOccurrences(of:with:)Recommended

replacingOccurrences(of:with:) replaces every match and returns a new String. It comes from Foundation, so the file needs import Foundation. The longer form takes options:, such as .caseInsensitive or .regularExpression, and a range: that limits the search to part of the string. To make several different replacements, apply them one after another.

replacing_occurrences.swift
import Foundation

let text = "The cat sat on the cat mat"

// Every match is replaced; the original stays as it was
let dogs = text.replacingOccurrences(of: "cat", with: "dog")
print(dogs)
print(text)

// A single character works the same way
print("2026-12-01".replacingOccurrences(of: "-", with: "/"))

// Ignore case
let names = "Swift, SWIFT, swift"
print(names.replacingOccurrences(of: "swift", with: "Swift",
                                 options: .caseInsensitive))

// Search only part of the string: from the first comma on
if let comma = names.firstIndex(of: ",") {
    let rest = comma..<names.endIndex
    print(names.replacingOccurrences(of: "swift", with: "Go",
                                     options: .caseInsensitive,
                                     range: rest))
}

// No match: you get the same text back
print("a-b".replacingOccurrences(of: "+", with: "*"))

// Several different replacements: apply them in order
let pairs = [("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")]
var html = "a < b && c > d"
for (from, to) in pairs {
    html = html.replacingOccurrences(of: from, with: to)
}
print(html)

Output

Both cats become dog, and printing text again shows it unchanged. With .caseInsensitive, all three spellings match. With range: starting at the first comma, the first Swift is left alone and the output is Swift, Go, Go. A search that finds nothing is not an error: a-b comes back as it was. In the last example the order matters: & goes first, otherwise the & inside &lt; would be replaced again. Without import Foundation, the compiler reports value of type 'String' has no member 'replacingOccurrences'.

2replacing(_:with:) and replace(_:with:) without Foundation

Swift 5.7 added replacing(_:with:) to the standard library, so it works with no import at all (on Apple platforms it needs macOS 13 or iOS 16). It returns a new string; its mutating twin replace(_:with:) changes a var in place. Both take maxReplacements: to stop after a number of matches. They compare whole Characters, so an emoji or an accented letter is matched as one unit, and they work on arrays as well as strings.

replacing.swift
// No import needed: replacing(_:with:) is in the standard library
let path = "docs/swift/strings"
print(path.replacing("/", with: " > "))

// replace(_:with:) changes a var in place
var greeting = "Hello, World"
greeting.replace("World", with: "Swift")
print(greeting)

// maxReplacements limits how many matches change
let csv = "name,age,city"
print(csv.replacing(",", with: ";", maxReplacements: 1))

// Matches whole Characters, so emoji are safe
let fruit = "I like 🍎 and 🍎!"
print(fruit.replacing("🍎", with: "🍐"))

// It works on any collection, arrays included
let codes = [1, 2, 0, 0, 3]
print(codes.replacing([0, 0], with: [9]))

Output

The slashes become docs > swift > strings, and replace turned greeting into Hello, Swift without a new constant. With maxReplacements: 1 only the first comma changed: name;age,city. Both apples became pears, and on the array the pair [0, 0] was swapped for [9]. There is no options: parameter here; for case-insensitive matching, pass a regex as in the next section.

3Replace with a regular expression

Foundation takes a pattern as a string with options: .regularExpression, and the replacement can refer to capture groups as $1, $2. Remember that a backslash is doubled inside a Swift string, so \d+ is written "\\d+". The standard library's replacing takes a regex literal, written #/\d+/# here (the bare /\d+/ form needs Swift 6 language mode or the bare-slash regex setting, and this page compiles in Swift 5 mode). Pass a closure instead of a string to compute each replacement from the match.

regex_replace.swift
import Foundation

let log = "user 42 paid 1500, user 7 paid 30"

// Foundation: a pattern string with the .regularExpression option
print(log.replacingOccurrences(of: "\\d+", with: "#",
                               options: .regularExpression))

// $1, $2, $3 in the template refer to the capture groups
let date = "2026-12-01"
print(date.replacingOccurrences(of: "(\\d+)-(\\d+)-(\\d+)",
                                with: "$3.$2.$1",
                                options: .regularExpression))

// In a pattern, . means any character
print("1.5.2".replacingOccurrences(of: ".", with: "-",
                                   options: .regularExpression))

// Standard library: a regex literal
print(log.replacing(#/\d+/#, with: "#"))

// A closure builds each replacement from the match
let doubled = log.replacing(#/\d+/#) { match in
    String((Int(match.output) ?? 0) * 2)
}
print(doubled)

// Named captures, and a case-insensitive regex
let people = "Lovelace Ada, Hopper Grace"
print(people.replacing(#/(?<last>\w+) (?<first>\w+)/#) { m in
    "\(m.first) \(m.last)"
})
print("Hello hello HELLO".replacing(#/hello/#.ignoresCase(), with: "hi"))

Output

Both forms turn every number into #. The template $3.$2.$1 reorders the date to 01.12.2026. The third line is the classic mistake: with .regularExpression, a . matches every character, so 1.5.2 becomes -----; drop the option to replace a literal dot, or escape it in the pattern. The closure doubles each number (user 84 paid 3000), named captures swap the names, and .ignoresCase() matches all three spellings of hello.

4Remove characters from a string

To delete a substring, replace it with an empty string. To delete a kind of character (digits, punctuation, spaces, a set of letters), filter is simpler: a string is a collection of Characters, and filter on a String returns a String with only the characters you keep. removeAll(where:) does the same to a var in place, and map swaps single characters for others. For spaces only at the ends, see trim whitespace.

remove_characters.swift
import Foundation

let phone = "(555) 123-4567"

// Delete a substring: replace it with ""
print(phone.replacingOccurrences(of: " ", with: ""))

// Keep only the characters you want
print(phone.filter(\.isNumber))
print("Hello, World!".filter { !$0.isPunctuation })
print("programming".filter { !"aeiou".contains($0) })

// removeAll(where:) edits a var in place
var tags = "  swift  ui  "
tags.removeAll(where: \.isWhitespace)
print(tags)

// Swap one character for another with map
let title = "replace all occurrences"
print(String(title.map { $0 == " " ? "-" : $0 }))

Output

Replacing " " with "" removes the one space and keeps the brackets and dash: (555)123-4567. Filtering with \.isNumber keeps only the digits, isPunctuation drops the comma and the exclamation mark, and the vowel filter leaves prgrmmng. removeAll(where:) took every space out of tags. map over a string gives an array of Characters, which is why the result is wrapped in String(…).

5Remove the last character

dropLast() returns everything but the last character as a Substring, a view into the original; wrap it in String(…) to store or return it. On an empty string it returns an empty result. removeLast() removes the last character from a var and returns it, but it crashes on an empty string with Fatal error: Can't remove last element from an empty collection. popLast() does the same job and returns nil instead. All of them work on characters, so an emoji is removed whole.

remove_last.swift
let word = "Swift!"

// dropLast() gives a Substring without the last character
let trimmed = word.dropLast()
print(trimmed, type(of: trimmed))
print(String(word.dropLast(3)))
print(String("".dropLast()).isEmpty)

// removeLast() edits a var and returns what it removed
var name = "Swift!"
let removed = name.removeLast()
print(name, removed)

// popLast() returns nil on an empty string instead of crashing
var empty = ""
print(String(describing: empty.popLast()))

// Remove a trailing slash only when there is one
var folder = "photos/"
if folder.hasSuffix("/") {
    folder.removeLast()
}
print(folder)

// removeLast(n) removes several characters
var file = "report.txt"
file.removeLast(4)
print(file)

// A character can be more than one code point: it goes whole
print(String("ok👍🏽".dropLast()))

Output

dropLast() printed Swift Substring: the text without the !, and the type you get back. dropLast(3) leaves Swi, and on an empty string the result is empty (true). removeLast() returned the ! it took off, so Swift ! is the shortened name followed by the removed character. The popLast() call printed nil where removeLast() would have crashed. removeLast(4) crashes too if the string is shorter, with Fatal error: Can't remove more items from a collection than it contains, so check count or use dropLast(4) when the length isn't known. The thumbs-up with a skin tone is two code points but one character, and it went in one step.

6Replace only the first (or last) occurrence

range(of:) finds the first match and gives back its range, or nil when there is none. Pass that range to replaceSubrange(_:with:) to change a var in place, or to replacingCharacters(in:with:) for a new string. Add options: .backwards to find the last match instead. The same pair also replaces the character at a position once you have its index; see get a substring for how string indexes work.

first_only.swift
import Foundation

let line = "one fish, two fish, red fish"

// The first match: range(of:) + replaceSubrange
var sentence = line
if let first = sentence.range(of: "fish") {
    sentence.replaceSubrange(first, with: "cat")
}
print(sentence)

// The last match: search backwards
if let last = line.range(of: "fish", options: .backwards) {
    print(line.replacingCharacters(in: last, with: "bird"))
}

// Without Foundation: replacing with maxReplacements: 1
print(line.replacing("fish", with: "cat", maxReplacements: 1))

// Replace the character at a position
var word = "cat"
let i = word.index(word.startIndex, offsetBy: 1)
word.replaceSubrange(i...i, with: "u")
print(word)

Output

Only the first fish became cat, and with .backwards only the last became bird. The standard library line gives the same result as the first one. Because range(of:) returns an optional, the if let also covers the case where there is no match, and nothing is changed. i...i is a one-character range, so cat becomes cut.

7Which should you use?

MethodNeedsWhat changesBest for
s.replacingOccurrences(of:with:)FoundationEvery match, new stringEveryday replacing, case-insensitive, regex patterns
s.replacing(_:with:)Standard libraryEvery match, or maxReplacementsNo Foundation, regex literals, closures
s.replace(_:with:)Standard libraryEvery match, in placeChanging a var
range(of:) + replaceSubrangeFoundationOne matchThe first match, or the last with .backwards
filter / removeAll(where:)Standard libraryCharacters that pass a testDeleting digits, punctuation, spaces
dropLast() / popLast()Standard libraryThe last characterTrimming the end, safe when empty
removeLast()Crashes when emptyThe last character, in placeA var you know is not empty

Frequently asked questions

How do I replace a character in a string in Swift?

Call text.replacingOccurrences(of: "a", with: "b") after import Foundation, or text.replacing("a", with: "b") without it. Both replace every match and return a new string. To change one character at a known position, get its index with index(_:offsetBy:) and call replaceSubrange(i...i, with: "u") on a var.

Why does String have no member replacingOccurrences?

Because the method comes from Foundation, not the standard library. Without import Foundation the compiler stops with "value of type 'String' has no member 'replacingOccurrences'". Add the import, or use the standard library replacing(_:with:), which needs none.

How do I remove the last character from a string in Swift?

String(text.dropLast()) returns the string without its last character and gives an empty string when the text is already empty. On a var, text.removeLast() removes it in place and returns it, but crashes on an empty string with "Fatal error: Can't remove last element from an empty collection". popLast() removes it in place and returns nil when the string is empty.

Does replacingOccurrences change the original string?

No. Swift strings are values, so replacingOccurrences(of:with:) and replacing(_:with:) return a new string and the original stays as it was. Assign the result back (text = text.replacingOccurrences(of: "a", with: "b")) or, on a var, call the mutating replace(_:with:).

What is the difference between replacing(_:with:) and replacingOccurrences(of:with:)?

replacingOccurrences is Foundation: it takes options: such as .caseInsensitive and .regularExpression (with $1 templates) and a range:. replacing is in the standard library since Swift 5.7: it needs no import, takes maxReplacements:, regex literals like #/\d+/# and a closure that builds each replacement, and works on arrays too.

How do I replace only the first occurrence?

Find it with range(of:) and replace that range: if let r = s.range(of: "fish") { s.replaceSubrange(r, with: "cat") }. Without Foundation, s.replacing("fish", with: "cat", maxReplacements: 1) does the same. For the last occurrence, use range(of: "fish", options: .backwards).

How do I replace several different strings at once?

Put the pairs in an array and apply them in order: for (from, to) in pairs { text = text.replacingOccurrences(of: from, with: to) }. The order matters when one replacement could create a match for another, as & does in HTML escaping, so replace & first. Use an array of pairs rather than a dictionary, because a dictionary iterates in a different order on each run.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground