---
title: "substring(with:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/nsstring/substring(with:)"
---

# substring(with:)

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

## Declaration

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

## Parameters

- `range`: A range. The range must not exceed the bounds of the receiver. Raises an doc://com.apple.foundation/documentation/Foundation/NSExceptionName/rangeException if (aRange.location - 1) or (aRange.location + aRange.length - 1) lies beyond the end of the receiver.

## Return Value

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

## Discussion

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.

## See Also

### Dividing Strings

- [components(separatedBy:)](foundation/nsstring/components(separatedby:)-238fy.md)
- [components(separatedBy:)](foundation/nsstring/components(separatedby:)-27x9g.md)
- [trimmingCharacters(in:)](foundation/nsstring/trimmingcharacters(in:).md)
- [substring(from:)](foundation/nsstring/substring(from:).md)
- [substring(to:)](foundation/nsstring/substring(to:).md)
