Convert string to URL by removing "\" - ios

I want to remove the \" from the begining and the end of the particular string to get the actual URL
Code: let = subString = originalString.replacingOccurrences(of: "\", with: "")
"\"https://api.example.com/deep-link?url=some_url_encoded_string\""
What I want is:
"https://api.example.com/deep-link?url=some_url_encoded_string"

You could trim the string in order to remove all the leading and trailing quote symbols:
let url = "\"https://some-server/some/path\""
let processedString = str.trimmingCharacters(in: .init(charactersIn: "\""))
print(processedString) // https://some-server/some/path
Note that \" is not a string made of two characters, but an escape sequence for the quote symbol.

If you want to remove \" wherever it is occurred in the string then use this:
let subString = originalString.replacingOccurrences(of: "\"", with: "")
if you want to remove it just in the beginning and the end of the string then you will check:
if originalString.first == "\"" {
_ = originalString.removeFirst()
}
if originalString.last == "\"" {
_ = originalString.popLast()
}

You have to remove character ".
like that.
let myString = "\"https://api.example.com/deep-link?url=some_url_encoded_string\""
let newString = myString.replacingOccurrences(of: "\", with: "").replacingOccurrences(of: """, with: "")
print(newString)

Check below code
let originalString = "\"https://api.example.com/deep-link?url=some_url_encoded_string\""
var temp = "\("\"")" as? String
if originalString.hasPrefix(temp!){
originalString.replacingOccurrences(of: "\"", with: "")
}

This backslash is here just because you need double quotes in string which otherwise wouldn't be possible in string declared on one line in Swift 4.2 or earlier.
In Swift 5 you could use raw string literals
let originalString = #""https...""#
So you actually need to remove just the only characters which are actually in string and they're double quotes (simplified: \" = ").
To do this you have to again use backslash before double quote "\" -> "\""
let subString = originalString.replacingOccurrences(of: "\"", with: "")

Related

Swift regex format to remove string contains brackets in iOS

Need to remove part of the string based on brackets.
For ex:
let str = "My Account (_1234)"
I wanted to remove inside brackets (_1234) and the result should be string My Account
Expected Output:
My Account
How can we achieve this with regex format or else using swift default class,need support on this.
Tried with separatedBy but it splits string into array but that is not the expected output.
str.components(separatedBy: "(")
Use replacingOccurrences(…)
let result = str.replacingOccurrences(of: #"\(.*\)"#,
with: "",
options: .regularExpression)
.trimmingCharacters(in: .whitespaces))
Regex ist not necessary. Just get the range of ( and extract the substring up to the lower bound of the range
let str = "My Account (_1234)"
if let range = str.range(of: " (") {
let account = String(str[..<range.lowerBound])
print(account)
}

How to convert any textfield input to float in Swift

I want to store float to CoreData and I want to convert every of the following inputs to 90.5:
90.5
90,5
90.5
90, 5
That means: Remove whitespace and convert , to .
Is this code best practice?
let str = " 90, 5 "
let converted = str.trimmingCharacters(in: .whitespacesAndNewlines)
let converted = strWithoutWithespace.replacingOccurrences(of: ",", with: ".")
No, it's not because it doesn't remove the space within the string.
The regex pattern "\\s+" removes all occurrences of one or more whitespace characters.
let str = " 90, 5 "
let strWithoutWhitespace = str.replacingOccurrences(of: "\\s+", with: "", options: .regularExpression)
let converted = strWithoutWhitespace.replacingOccurrences(of: ",", with: ".")

How to replace occurences in string using groups in Swift?

I simply need to replace:
<p>, <div>
with
\n<p>, \n<div>
in string with one single pattern replacing. Is it possible?
let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>", with: "\n<p>").replacingOccurrences(of: "<div>", with: "\n<div>")
is there a better solution with regex?
You can do a regular expression search, with a template in the replacement
string:
let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>|<div>", with: "\n$0", options: .regularExpression)
For each match, the $0 template is replaced by what actually matched the pattern.

Remove U\0000fffc unicode scalar from string

I receive an NSAttributedString that contains a NSTextAttachment. I want to remove that attachment, and it looks like it is represented as "\u{ef}" in the string. Printing the unicode scalars of such string, it also seems that unicode scalar for the "\u{ef}" is U\0000fffc.
I tried to do this:
noAttachmentsText = text.replacingOccurrences(of: "\u{ef}", with: "")
with no success, so I'm trying by comparing unicode scalars:
var scalars = Array(text.unicodeScalars)
for scalar in scalars {
// compare `scalar` to `U\0000fffc`
}
but I'm not able either to succeed in the comparison.
How could I do this?
But this code works for me from How do I remove "\U0000fffc" from a string in Swift?
let original = "First part \u{ef} Last part"
let originalRange = Range<String.Index>(start: original.startIndex, end: original.endIndex)
let target = original.stringByReplacingOccurrencesOfString("\u{ef}", withString: "", options: NSStringCompareOptions.LiteralSearch, range: originalRange)
print(target)
Output :
"First part ï Last part"
to
First part Last part
U can use similar code for swift 3 just replace unicode using replacingOccurrences option for exapmle :
func stringTocleanup(str: String) -> String {
var result = str
result = result.replacingOccurrences(of: "\"", with: "\"")
.replacingOccurrences(of: "\u{10}", with: "")
return result
}

Swift - Remove " character from string

I have a string which is "Optional("5")". I need to remove the "" surrounding the 5. I have removed the 'Optional' by doing:
text2 = text2.stringByReplacingOccurrencesOfString("Optional(", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
I am having difficulties removing the " characters as they designate the end of a string in the code.
Swift uses backslash to escape double quotes. Here is the list of escaped special characters in Swift:
\0 (null character)
\\ (backslash)
\t (horizontal tab)
\n (line feed)
\r (carriage return)
\" (double quote)
\' (single quote)
This should work:
text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)
Swift 3 and Swift 4:
text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)
Latest documents updated to Swift 3.0.1 have:
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n}), where n is between one and eight hexadecimal digits
If you need more details you can take a look to the official docs here
Here is the swift 3 updated answer
var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n})
To remove the optional you only should do this
println("\(text2!)")
cause if you dont use "!" it takes the optional value of text2
And to remove "" from 5 you have to convert it to NSInteger or NSNumber easy peasy. It has "" cause its an string.
Replacing for Removing is not quite logical.
String.filter allows to iterate a string char by char and keep only true assertion.
Swift 4 & 5
var aString = "Optional(\"5\")"
aString = aString.filter { $0 != "\"" }
> Optional(5)
Or to extend
var aString = "Optional(\"5\")"
let filteredChars = "\"\n\t"
aString = aString.filter { filteredChars.range(of: String($0)) == nil }
> Optional(5)
I've eventually got this to work in the playground, having multiple characters I'm trying to remove from a string:
var otherstring = "lat\" : 40.7127837,\n"
var new = otherstring.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "la t, \n \" ':"))
count(new) //result = 10
println(new)
//yielding what I'm after just the numeric portion 40.7127837
If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:
someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])
As Martin R says, your string "Optional("5")" looks like you did something wrong.
dasblinkenlight answers you so it is fine, but for future readers, I will try to add alternative code as:
if let realString = yourOriginalString {
text2 = realString
} else {
text2 = ""
}
text2 in your example looks like String and it is maybe already set to "" but it looks like you have an yourOriginalString of type Optional(String) somewhere that it wasn't cast or use correctly.
I hope this can help some reader.
Swift 5 (working). Only 1 line code.
For removing single / multiple characters.
trimmingCharacters(in: CharacterSet)
In action:
var yourString:String = "(\"This Is: Your String\")"
yourString = yourString.trimmingCharacters(in: ["("," ",":","\"",")"])
print(yourString)
Output:
ThisIsYourString
You are entering a Set that contains characters you're required to trim.
Let's say you have a string:
var string = "potatoes + carrots"
And you want to replace the word "potatoes" in that string with "tomatoes"
string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)
If you print your string, it will now be: "tomatoes + carrots"
If you want to remove the word potatoes from the sting altogether, you can use:
string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)
If you want to use some other characters in your sting, use:
Null Character (\0)
Backslash (\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Example:
string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)
Output: "dog's toys + carrots"
If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:
if value != nil
{ print(value)
}
or you can use this:
if let value = text {
print(value)
}
or in simple just 1 line answer:
print(value ?? "")
The last line will check if variable 'value' has any value assigned to it, if not it will print empty string
You've instantiated text2 as an Optional (e.g. var text2: String?).
This is why you receive Optional("5") in your string.
take away the ? and replace with:
var text2: String = ""
If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:
if let value = text {
print(value)
}
Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.

Resources