how to remove backslash from the value of an array - ruby-on-rails

I have following type of arrays
["def, \" \""]
["abc,\" \",def"]
How can i check if there's a \ in value and convert them correctly as follows?
["def", " "]
["abc", " ", "def"]
I have been trying to correct them using
join(',')
delete('\"') split(', ')
but no luck

When you write:
input = "{ \"foo\": \"bar\", \"num\": 3}"
The actual string stored in input is:
{ "foo": "bar", "num": 3}
The escape \" here is interpreted by Ruby parser, so that it can distinguish between the boundary of a string (the left most and the right most "), and a normal character " in a string (the escaped ones).
String#delete deletes a character set specified the first parameter, rather than a pattern. All characters that is in the first parameter will be removed. So by writing
input.delete('\\"')
You got a string with all \ and " removed from input, rather than a string with all \" sequence removed from input. This is wrong for your case. It may cause unexpected behavior some time later.

Related

How to split by special character "\" in Lua?

I tried to split by "\", but this character is so special in Lua, even if I use escape character "%", the IDE shows an error Unterminated String constant
local index = string.find("lua. is \wonderful", "%\", 1)
To insert backslash \ into a quoted string, escape it with itself: "\\". \ is the escape character in regular quoted strings, so it is escaped with \. Or you can use the long string syntax, which doesn't allow escape sequences, as already pointed out: [[\]].
Percent is only an escape character in a string that is being used as a pattern, so it is used before the magical characters ^$()%.[]*+-? in the second argument to string.find, string.match, string.gmatch, and string.gsub, and %% represents % in the third argument to string.gsub.
The percent is still there in the string that is stored in memory, but backslash escape sequences are replaced with the corresponding character. \\ becomes \ when the string is stored in memory, and if you count the number of backslashes in a string "\\" using string.gsub, it will only find one: select(2, string.gsub("\\", "\\", "")) returns 1.

Remove "\" when we add as a value to dictionary

I have to add value for a key in a dictionary the value is JSON string but it should not have "\" or "\n" in the value,
I tried to remove them and created a string to set the value for key in dictionary but when i add the value to key it automatically adds "\" but when i check the string "\" are not there.
Please let me know if anyone has faced this issue
Value(Json String): Need to set for "CartProducts" Key in the dictionary
[{"type":"radio","product_option_value_id":"633","value":"Medium(40c)","option_value_id":"49","product_option_id":"49","option_id":"56","name":"Medium(40c)"}]
dictionary {
account = guest;
CartProducts = "[{\"product_id\":\"56\",\"option\":\"[{\"type\":\"radio\",\"product_option_value_id\":\"633\",\"value\":\"Medium(40c)\",\"option_value_id\":\"49\",\"product_option_id\":\"49\",\"option_id\":\"56\",\"name\":\"Medium(40c)\"}]\",\"quantity\":\"1\",\"category\":\"Cappuccino\",\"price\":\"3.90\",\"model\":\"Coffee\",\"delivery_date\":\"2016-04-2006:00:01+0000\",\"total\":\"3.90\",\"name\":\"Cappuccino\"}]";
}
Need to remove "\" from the key "CartProducts" in the dictionary "dictionary"
\" in this case is an escape character. It is used to distinguish quotes within quotes.
Take an example:
Product = "my example variable = "hello""
the quotes in this case clashes. To the compiler it looks like
Product = "my example variable = "
//Ouside quotes
hello
//empty quotes at the end
""
Basically it is a mess. So the work around is to use \" which is treated as a single character but is considered part of the string as ".
Other example of escape characters:
\' single quote '
\n new line
\t tab
\\ backslash \

Removing single backslash from string

I am getting a string for a place name back from an API: "Moe\'s Restaurant & Brewhouse". I want to just have it be "Moe's Restaurant & Brewhouse" but I can't get it to properly format without the \.
I've seen the other posts on this topic, I've tried placeName?.stringByReplacingOccurrencesOfString("\\", withString: "") and placeName?.stringByReplacingOccurrencesOfString("\'", withString: "'"). I just can't get anything to work. Any ideas so I can get the string how I want it without the \? Any help is greatly appreciated, thanks!!
You report that the API is returning "Moe\'s Restaurant & Brewhouse". More than likely you are looking at a Swift dictionary or something like that and it is showing you the string literal representation of that string. But depending upon how you're printing that, the string most likely does not contain any backslash.
Consider the following:
let string = "Moe's"
let dictionary = ["name": string]
print(dictionary)
That will print:
["name": "Moe\'s"]
It is just showing the "string literal" representation. As the documentation says:
String literals can include the following special characters:
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
But, note, that backslash before the ' in Moe\'s is not part of the string, but rather just an artifact of printing a string literal with an escapable character in it.
If you do:
let string2 = dictionary["name"]!
print(string2)
It will show you that there is actually no backslash there:
Moe's
Likewise, if you check the number of characters:
print(dictionary["name"]!.characters.count)
It will correctly report that there are only five characters, not six.
(For what it's worth, I think Apple has made this far more confusing than is necessary because it sometimes prints strings as if they were string literals with backslashes, and other times as the true underlying string. And to add to the confusion, the single quote character can be escaped in a string literal, but doesn't have to be.)
Note, if your string really did have a backslash in it, you are correct that this is the correct way to remove it:
someString.stringByReplacingOccurrencesOfString("\\", withString: "")
But in this case, I suspect that the backslash that you are seeing is an artifact of how you're displaying it rather than an actual backslash in the underlying string.

Swift - remove single backslash

this is maybe stupid question but I'm new to swift and i actually can't figure this out.
I have API which returns url as string "http:\/\/xxx". I don't know how to store URL returned from API in this format. I can't store it to variable because of backslash.
From apple doc:
...string cannot contain an unescaped backslash (\), ...
Is there any way how to store string like this or how remove these single backslashes or how to work with this?
Thank you for every advice.
You can just replace those backslashes, for example:
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
Or, to avoid the confusion over the fact that the backslash within a normal string literal is escaped with yet another backslash, we can use an extended string delimiter of #" and "#:
let string2 = string1.stringByReplacingOccurrencesOfString(#"\"#, withString: "")
But, if possible, you really should fix that API that is returning those backslashes, as that's obviously incorrect. The author of that code was apparently under the mistaken impression that forward slashes must be escaped, but this is not true.
Bottom line, the API should be fixed to not insert these backslashes, but until that's remedied, you can use the above to remove any backslashes that may occur.
In the discussion in the comments below, there seems to be enormous confusion about backslashes in strings. So, let's step back for a second and discuss "string literals". As the documentation says, a string literal is:
You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").
Note, a string literal is just a representation of a particular fixed sequence of characters in your code. But, this should not be confused with the underlying String object itself. The key difference between a string literal and the underlying String object is that a string literal allows one to use a backslash as an "escape" character, used when representing special characters (or doing string interpolation). As the documentation says:
String literals can include the following special characters:
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, you are correct that in a string literal, as the excerpt you quoted above points out, you cannot have an unescaped backslash. Thus, whenever you want to represent a single backslash in a string literal, you represent that with a \\.
Thus the above stringByReplacingOccurrencesOfString means "look through the string1, find all occurrences of a single backslash, and replace them with an empty string (i.e. remove the backslash)."
Consider:
let string1 = "foo\\bar"
print(string1) // this will print "foo\bar"
print(string1.characters.count) // this will print "7", not "8"
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
print(string2) // this will print "foobar"
print(string2.characters.count) // this will print "6"
A little confusingly, if you look at string1 in the "Variables" view of the "Debug" panel or within playground, it will show a string literal representation (i.e. backslashes will appear as "\\"). But don't be confused. When you see \\ in the string literal, there is actually only a single backslash within the actual string. But if you print the value or look at the actual characters, there is only a single backslash in the string, itself.
In short, do not conflate the escaping of the backslash within a string literal (for example, the parameters to stringByReplacingOccurrencesOfString) and the single backslash that exists in the underlying string.
I found I was having this same issue when trying to encode my objects to JSON. Depending on if you're using the newer JSONEncoder class to parse your JSON and you're supporting a minimum of iOS 13, you can use the .withoutEscapingSlashes output formatting:
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
try encoder.encode(yourJSONObject)
Please check the below code.
let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let convertedStr = jsonStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
print(convertedStr)
I've solved with this piece of code:
let convertedStr = jsonString.replacingOccurrences(of: "\\/", with: "/")
To remove single backslash,try this
let replaceStr = backslashString.replacingOccurrences(of: "\"", with: "")
Include a backslash in a string by adding an extra backslash.

(Swift) how to print "\" character in a string?

I have tried to print it but it just by passes because it's an escaped character.
e.g output should be as follows.
\correct
For that and also future reference:
\0 – Null character (that is a zero after the slash)
\\ – Backslash itself. Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t – Horizontal tab
\n – Line Feed
\r – Carriage Return
\” – Double quote. Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’ – Single Quote. Similar reason to above.
Use the following code for Swift 5, Xcode 10.2
let myText = #"This is a Backslash: \"#
print(myText)
Output:
This is a Backslash: \
Now not required to add a double slash to use a single slash in swift 5, even now required slash before some character, for example, single quote, double quote etc.
See this post for latest update about swift 5
https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0
var s1: String = "I love my "
let s2: String = "country"
s1 += "\"\(s2)\""
print(s1)
It will print I love my "country"
The backslash character \ acts as an escape character when used in a string. This means you can use, for example, double quotes, in a string by pre-pending them with \. The same also applies for the backslash character itself, which is to say that println("\\") will result in just \ being printed.

Resources