---
title: "addingPercentEncoding(withAllowedCharacters:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/nsstring/addingpercentencoding(withallowedcharacters:)"
---

# addingPercentEncoding(withAllowedCharacters:)

Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.

## Declaration

```swift
func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?
```

## Parameters

- `allowedCharacters`: The characters not replaced in the string. Typically, you specify one of the predefined character sets for a particular URL component, such as doc://com.apple.foundation/documentation/Foundation/NSCharacterSet/urlPathAllowed or doc://com.apple.foundation/documentation/Foundation/NSCharacterSet/urlQueryAllowed.

## Return Value

Return Value Returns the encoded string, or nil if the transformation is not possible.

## Discussion

Discussion Entire URL strings cannot be percent-encoded, because each URL component specifies a different set of allowed characters. For example, the query component of a URL allows the “@” character, but that character must be percent-encoded in the password component. UTF-8 encoding is used to determine the correct percent-encoded characters. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored. important: You must not call this method on strings that are already percent-encoded. Calling this method on strings that are already percent-encoded will cause percent characters in a percent-encoded sequence to be percent-encoded twice.

## See Also

### Related Documentation

- [replacingPercentEscapes(using:)](foundation/nsstring/replacingpercentescapes(using:).md)
- [addingPercentEscapes(using:)](foundation/nsstring/addingpercentescapes(using:).md)

### Working with URL Strings

- [removingPercentEncoding](foundation/nsstring/removingpercentencoding.md)
