---
title: "replaceOccurrences(of:with:options:range:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/nsmutablestring/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.

## Declaration

```swift
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 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

Return Value The number of replacements made.

## Discussion

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

## See Also

### Modifying a String

- [append(_:)](foundation/nsmutablestring/append(_:).md)
- [applyTransform(_:reverse:range:updatedRange:)](foundation/nsmutablestring/applytransform(_:reverse:range:updatedrange:).md)
- [deleteCharacters(in:)](foundation/nsmutablestring/deletecharacters(in:).md)
- [insert(_:at:)](foundation/nsmutablestring/insert(_:at:).md)
- [replaceCharacters(in:with:)](foundation/nsmutablestring/replacecharacters(in:with:).md)
- [setString(_:)](foundation/nsmutablestring/setstring(_:).md)
