<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSMutableString/replaceOccurrences(of:with:options:range:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSMutableString(im)replaceOccurrencesOfString:withString:options:range:"
  },
  "title" : "replaceOccurrences(of:with:options:range:)"
}
-->

# replaceOccurrences(of:with:options:range:)

Replaces all occurrences of a given string in a given range with another given string, returning the number of replacements.

```
func replaceOccurrences(of target: String, with replacement: String, options: NSString.CompareOptions = [], range searchRange: NSRange) -> Int
```

## Parameters

`target`

The string to replace.
  
  > Important:
  > Raises an `NSInvalidArgumentException` if `target` is `nil`.

`replacement`

The string with which to replace `target`.
  
  > Important:
  > Raises an `NSInvalidArgumentException` if `replacement` is `nil`.

`options`

A mask specifying search options. See [String Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/introStrings.html#//apple_ref/doc/uid/10000035i) for details.

    If     `opts`     is     `NSBackwardsSearch`    , the search is done from the end of the range. If     `opts`     is     `NSAnchoredSearch`    , only anchored (but potentially multiple) instances are replaced.     `NSLiteralSearch`     and     `NSCaseInsensitiveSearch`     also apply.

`searchRange`

The range of characters to replace. `searchRange` must not exceed the bounds of the receiver. Specify `searchRange` as `NSMakeRange(0, [receiver length])` to process the entire string.
  
  > Important:
  > Raises an `NSRangeException` if any part of `searchRange` lies beyond the end of the receiver.

## Return Value

The number of replacements made.

## Discussion

This method treats the length of the string as a valid range value that returns an empty string.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)