0

and I want to replace \/ and \ character with /. Hence I used string's replacingOccurrences function, but it generates error as "Invalid escape sequence in literal". Below is my string, and replacingOccurrence function. Also I have attached screenshot for the same.kindly help

error screenshot

var str = "http:\/\/colesi.com\/exapp\/upload.png"
let ans = str.replacingOccurrences(of: "\/", with: "/")
let ansq = str.replacingOccurrences(of: "\", with: "")
rmaddy
  • 314,917
  • 42
  • 532
  • 579
iOS Dev
  • 33
  • 2
  • 8
  • further more you can also see https://stackoverflow.com/questions/31287879/invalid-escape-sequence-in-literal – Niroj Dec 27 '17 at 15:52

1 Answers1

3

You need to understand what \ is used for, it is for escaping special characters, like " inside a string. You cannot write let str = " " " but you need to write let str = " \" ". Since \ is treated specially you need to escape it when trying to write it literally: let str = " \\ " instead of let str = " \ " . / itself is not "escapable", \/ does not mean anything and is invalid.

That means in your particular case all three shown lines are invalid. Either it should be

var str = "http:\\/\\/colesi.com\\/exapp\\/upload.png"

or

var str = "http://colesi.com/exapp/upload.png"

to start with. In the second case you dont need to do anything.

In the first case you need to do

let ans = str.replacingOccurrences(of: "\\", with: "")

I am gussing here: I think you copied that url from somewhere where it has been escaped in some way and are trying to counteract that, chances are you do not need to do that at all.

luk2302
  • 55,258
  • 23
  • 97
  • 137