Gazzini
Gazzini

Reputation: 738

Remove percent-escaped characters from string

How do I remove, not decode, percent-escaped characters from a string using Swift. For instance:

"hello%20there" should become "hellothere"

EDIT:

I would like to replace multiple percent-escaped characters in a string. So: "hello%20there%0Dperson" should become "hellothereperson"

Upvotes: 1

Views: 3408

Answers (4)

Vidyalaxmi
Vidyalaxmi

Reputation: 309

You can use the method "removingPercentEncoding"

let precentEncodedString = "hello%20there%0Dperson"
let decodedString = precentEncodedString.removingPercentEncoding ?? ""

Upvotes: 2

Henawey
Henawey

Reputation: 558

let input:String = "hello%20there%0Dperson"

 guard let output = input.stringByRemovingPercentEncoding else{
      NSLog("failed to remove percent encoding")
      return
  }

 NSLog(output)

and the result is

hello there
person

then you can just remove the spaces

or you can remove it by regex

"%([0-9a-fA-F]{2})"

Upvotes: 1

Felipe Sabino
Felipe Sabino

Reputation: 18225

You can use regex for that matching % followed by two numbers: %[0-9a-fA-F]{2}

let myString = "hello%20there%0D%24person"
let regex = try! NSRegularExpression(pattern: "%[0-9a-fA-F]{2}", options: [])
let range = NSMakeRange(0, myString.characters.count)
let modString = regex.stringByReplacingMatchesInString(myString,
                                                       options: [],
                                                       range: range,
                                                       withTemplate: "")
print(modString)

Upvotes: 1

ZhangChn
ZhangChn

Reputation: 3184

let string = originalString.replacingOccurrences(of: "%[0-9a-fA-F]{2}", 
                                                 with: "",
                                                 options: .regularExpression, 
                                                 range: nil)

Upvotes: 8

Related Questions