2

I am currently trying to setup a string to be added to a HTTP POST request where a user would type text and tap 'enter' and a request would be sent.

I know multiple characters (^,+,<,>) can be replaced with a single character ('_') like so:

userText.replacingOccurrences(of: "[^+<>]", with: "_"

I currently am using multiple functions of:

.replacingOccurrences(of: StringProtocol, with:StringProtocol)

like so:

let addAddress = userText.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: ".", with: "%2E").replacingOccurrences(of: "-", with: "%2D").replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29").replacingOccurrences(of: ",", with: "%2C").replacingOccurrences(of: "&", with: "%26")

Is there a more efficient way of doing this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
MrPickles2009
  • 117
  • 4
  • 10

3 Answers3

1

What you are doing is to manually encode the string with a percent encoding.

If that's the case, this will help you:

addingPercentEncoding(withAllowedCharacters:)

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

https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

For your specific case this should work:

userText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

Community
  • 1
  • 1
nikano
  • 1,136
  • 1
  • 8
  • 18
0

Ideally to use .urlHostAllowed CharacterSet since it works almost always.

textInput.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

But the best is combining all the possible options like here which will make sure you make it right.

Tung Fam
  • 7,899
  • 4
  • 56
  • 63
0

I think the only problem you will run into with using addingPercentEncoding is that your question states that a space " " should be replaced with an underscore. Using addingPercentEncoding for a space " " will return %20. You should be able to combine some of these answers, define the remaining characters from your list that should return standard character replacement and get your desired outcome.

var userText = "This has.lots-of(symbols),&stuff"
userText = userText.replacingOccurrences(of: " ", with: "_")
let allowedCharacterSet = (CharacterSet(charactersIn: ".-(),&").inverted)
var newText = userText.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)

print(newText!) // Returns This_has%2Elots%2Dof%28symbols%29%2C%26stuff
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Parrett Apps
  • 569
  • 1
  • 4
  • 14