Swift: Remove Leading and Trailing Whitespace of a String

Updated: February 23, 2023 By: Wolf Post a comment

This practical article walks you through a couple of different examples that demonstrate how to remove leading and trailing whitespace, separately or together, from a string in Swift.

Trim both leading and trailing whitespace

You can use the built-in trimmingCharacters(in:) method with the CharacterSet.whitespaces argument to remove both leading and trailing whitespace from a string.

Example:

import Foundation

let str = "  slingacademy.com   "
let trimmedStr = str.trimmingCharacters(in: .whitespaces)

print(trimmedStr) 
print("The length of the original string is \(str.count)")
print("The length of the trimmed string is \(trimmedStr.count)")

Output:

slingacademy.com
The length of the original string is 21
The length of the trimmed string is 16

A common real-world use case for trimming both leading and trailing whitespace is cleaning up user input from a text field or removing extraneous whitespace from a file name.

Only remove the leading whitespace

There might be cases where you only want to trim the leading white space of a given string. The example below will show you how to do that.

Example:

import Foundation

let str = "   Trim leading whitespace, preserve trailing whitespace.  "

let leadingWhitespace = str.prefix(while: {$0.isWhitespace})
let trimmedStr = String(str[leadingWhitespace.endIndex...])
print("Output: '\(trimmedStr)'") 

Output:

Output: 'Trim leading whitespace, preserve trailing whitespace.  '

You can also use regular expressions to handle this task:

import Foundation

let str = "   Trim leading whitespace, preserve trailing whitespace.  "
let pattern = "^\\s+"
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(str.startIndex..., in: str)
let trimmed = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "")

print("Output: '\(trimmed)'")

Output:

Output: 'Trim leading whitespace, preserve trailing whitespace.  '

Only remove trailing whitespace

Real-world use cases for this might include formatting text for display, such as preserving the indentation of code blocks or working with text files that have whitespace at the beginning of each line.

You can use the replacingOccurrences() method with a regular expression pattern to remove the trailing whitespace (and still keep the leading whitespace) from a string.

Example:

import Foundation

let str = "   Remove trailing whitespace but keep leading whitespace     "
let pattern = "\\s+$"
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(str.startIndex..., in: str)
let trimmed = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "")

print("Trimmed: \(trimmed)")
print("Lenght of original string: \(str.count)")
print("Lenght of trimmed string: \(trimmed.count)")

Output:

Trimmed:    Remove trailing whitespace but keep leading whitespace
Lenght of original string: 62
Lenght of trimmed string: 57