<!--
{
  "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/NSString/substring(with:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSString(im)substringWithRange:"
  },
  "title" : "substring(with:)"
}
-->

# substring(with:)

Returns a string object containing the characters of the receiver that lie within a given range.

```
func substring(with range: NSRange) -> String
```

## Parameters

`range`

A range. The range must not exceed the bounds of the receiver.

    Raises an [`rangeException`](/documentation/Foundation/NSExceptionName/rangeException)     if (    `aRange.location`     - 1) or (    `aRange.location`     +     `aRange.length`     - 1) lies beyond the end of the receiver.

## Return Value

A string object containing the characters of the receiver that lie within `aRange`.

## Discussion

This method detects all invalid ranges (including those with negative lengths). For applications linked against macOS 10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.

---

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)