let result = ["response": response,
"callbackId": callbackId]
do {
let data = try NSJSONSerialization.dataWithJSONObject(result, options: .PrettyPrinted)
var str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
str = str?.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
str = str?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
str = str?.stringByReplacingOccurrencesOfString("\'", withString: "\\\'")
str = str?.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
str = str?.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
// str = str?.stringByReplacingOccurrencesOfString("\f", withString: "\\f")
// str = str?.stringByReplacingOccurrencesOfString("\u2028", withString: "\\u2028")
// str = str?.stringByReplacingOccurrencesOfString("\u2029", withString: "\\u2029")
return "bridge.invokeJs('{\"response\" : {\"username\" : \"zhongan\"},\"callbackId\" : \(callbackId)}')"
} catch {
return nil
}
I want to convert the json string to js script, and then call evaluateJavaScript, but can not convert the special character, like \f \u2029, this will give a compiler error and I don't know why.
Have a look at Strings and Characters Section Special Characters in String Literals.
According to this page \f is not defined.
The escaped special characters \0 (null character), \ (backslash), \t
(horizontal tab), \n (line feed), \r (carriage return), \" (double
quote) and \' (single quote)
An arbitrary Unicode scalar, written as
\u{n}, where n is a 1–8 digit hexadecimal number with a value equal to
a valid Unicode code point
So
\f Form Feed you may be written in escaped form as \u{000C}
\u2029 Page Feed has to be escaped as \u{2029}
\u2028 Line Separator has to be escaped as \u{2028}
See also "Unicode Control Characters"
Related
I referred this SO post to remove whitespaces and newline characters from a string. But in my string, I may have extra whitespaces as well as extra newline characters. I want to remove the unnecessary \n's and whitespaces from that string.
But if there is a string like so..."This \n is a st\tri\rng" then I don't want Thisisastring as the result but instead something like this..
This is a string
To replace contiguous spaces with a single space, replace Regular Expression \s+ with a single space:
let str = "This \n\n is a string"
if let regex = try? NSRegularExpression(pattern: "\\s+", options: NSRegularExpression.Options.caseInsensitive)
{
let result = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.count), withTemplate: " ")
print(result) //output: "This is a string"
}
I'm trying to replace some HTML codes in Swift with the appropriate characters. I used a String extension.
extension String {
mutating func fix_HTML_Codes() {
let originalString = self
let newString = originalString.replacingOccurrences(of: "'", with: "\'")
let newString2 = newString.replacingOccurrences(of: """, with: "\"")
self = newString2
}
}
However, instead of replacing my escaped single quote with a single quote, it actually replaces it with \', anyone know why?
Here's an example of what I'm getting:
"On which Beatles album would you find the song \'Eleanor Rigby\'?"
It's including the escape character.
Code to get the string before a certain character:
let string = "Hello World"
if let range = string.range(of: "World") {
let firstPart = string[string.startIndex..<range.lowerBound]
print(firstPart) // print Hello
}
To begin with, I have a program that converts Hex float to a Binary float and I want to remove all "0" from Binary string answer until first "1". Example:
Any ideas?
You can use Regular Expression:
var str = "001110111001"
str = str.replacingOccurrences(of: "0", with: "", options: [.anchored], range: nil)
The anchored option means search for 0s at the start of the string only.
I have multiple lines in an String, for example:
let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"
Now i want to remove the whole sentence between "Mieter" and the line break. So the result should be:
let str = "Verwalter: Michael Karner \n"
I could check with Regex, but i am only able to get the string between 2 words. For example with:
if let match = str.rangeOfString("(?<=Mieter)[^\n]+", options: .RegularExpressionSearch) {
print(str.substringWithRange(match)) // between
}
But how can i replace a whole line?
Edit:
It is not working anymore when its between a string:
let str = "Test \n Mieter: \n Hausverwalter: \n Firma: \n"
str.stringByReplacingOccurrencesOfString("^Mieter[^\n]+\\s", withString: "", options: .RegularExpressionSearch, range: nil)
// so "Mieter \n" is not being replaced.
Use replacingOccurrencesOf
let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"
str.replacingOccurrences(of: "^Mieter[^\n]+\\s", with: "", options: .regularExpression)
This is Swift 3 code
Edit:
If the substring is not at the beginning of the string remove the leading caret (^).
I'm trying to remove the last punctuation of a string in swift 2.0
var str: String = "This is a string, but i need to remove this comma, \n"
var trimmedstr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
First I'm removing the the white spaces and newline characters at the end, and then I need to check of the last character of trimmedstr if it is a punctuation. It can be a period, comma, dash, etc, and if it is i need to remove it it.
How can i accomplish this?
There are multiple ways to do it. You can use contains to check if the last character is in the set of expected characters, and use dropLast() on the String to construct a new string without the last character:
let str = "This is a string, but i need to remove this comma, \n"
let trimmedstr = str.trimmingCharacters(in: .whitespacesAndNewlines)
if let lastchar = trimmedstr.last {
if [",", ".", "-", "?"].contains(lastchar) {
let newstr = String(trimmedstr.dropLast())
print(newstr)
}
}
Could use .trimmingCharacters(in:.whitespacesAndNewlines) and .trimmingCharacters(in: .punctuationCharacters)
for example, to remove whitespaces and punctuations on both ends of the String-
let str = "\n This is a string, but i need to remove this comma and whitespaces, \t\n"
let trimmedStr = str.trimmingCharacters(in:
.whitespacesAndNewlines).trimmingCharacters(in: .punctuationCharacters)
Result -
This is a string, but i need to remove this comma and whitespaces