<!--
{
  "availability" : [
    "macOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "AppKit",
  "identifier" : "/documentation/AppKit/NSText/replaceCharacters(in:with:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "AppKit"
    ],
    "preciseIdentifier" : "c:objc(cs)NSText(im)replaceCharactersInRange:withString:"
  },
  "title" : "replaceCharacters(in:with:)"
}
-->

# replaceCharacters(in:with:)

Replaces the characters in the given range with those in the given string.

```
func replaceCharacters(in range: NSRange, with string: String)
```

## Parameters

`range`

The range of characters to be replaced.

`string`

The replacement string.

## Discussion

For a rich text object, the text of `aString` is assigned the formatting attributes of the first character of the text it replaces, or of the character immediately before `aRange` if the range’s length is 0. If the range’s location is 0, the formatting attributes of the first character in the receiver are used.

This method does not include undo support by default. Clients must invoke [`shouldChangeText(inRanges:replacementStrings:)`](/documentation/AppKit/NSTextView/shouldChangeText(inRanges:replacementStrings:)) or [`shouldChangeText(in:replacementString:)`](/documentation/AppKit/NSTextView/shouldChangeText(in:replacementString:)) to include this method in an undoable action.

In most cases, programmatic modification of the text is best done by operating on the text storage directly, using the general methods of <doc://com.apple.documentation/documentation/Foundation/NSMutableAttributedString>.

---

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)