BarabulkaForever
BarabulkaForever

Reputation: 53

How to delete \ (backslash) from string swift

I have a problem with backslash in strings.

When i create a string with this code:

 let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi

I expect this URL

https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0

But I get this

https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq \'Recommended\'&?ZUMO-API-VERSION=2.0.0

I tried to delete them using

stringByReplacingOccurrencesOfString("\\", withString: "")

But it doesn't help. Also I tried to add backslash before the ' but it doesn't help.

Upvotes: 0

Views: 842

Answers (3)

jrturton
jrturton

Reputation: 119242

Use NSURLComponents and NSURLQueryItem to build URLs, not string concatenation.

let components = NSURLComponents()
components.scheme = "https"
components.host = "swoup.azurewebsites.net"
components.path = "/tables/coupon"
let category = "Recommended"
let expand = NSURLQueryItem(name: "expand", value: "source")
let filter = NSURLQueryItem(name: "filter", value: "Source/Name eq '\(category)'")
let api = NSURLQueryItem(name:"ZUMO-API-VERSION", value:"2.0.0")
components.queryItems = [expand, filter, api]

Gives you this URL from components.URL:

https://swoup.azurewebsites.net/tables/coupon?expand=source&filter=Source/Name%20eq%20\'Recommended\'&ZUMO-API-VERSION=2.0.0

Upvotes: 0

zaph
zaph

Reputation: 112857

The error is in the variables that are not shown.

With this example complete (?) code example:

let webProtocol = "https://"
let siteHost = "swoup.azurewebsites.net"
let category = "Recommended"
let siteApi = "ZUMO-API-VERSION=2.0.0"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print (url)

Output
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0

There is no \.

Upvotes: 0

Ogre Codes
Ogre Codes

Reputation: 19621

It's not clear based on your question, but I believe the backslashes are not actually in the string, but being printed by XCode. For example, enter the following into a playground:

let siteApi="test=123"
let category="Category1"
let webProtocol="https://"
let siteHost="www.testme.com"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print( url)

And you will see the output does not contain backslashes.

https://www.testme.com/tables/coupon?$expand=source&$filter=Source/Name eq 'Category1'&test=123

Upvotes: 1

Related Questions