The Coffeescript docs contain the following blurb
String Interpolation, Block Strings, and Block Comments
Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.
Can someone explain what "single-quoted strings are literal" means here?
Does it just mean that there will be no interpretation? Is there a more javascripty meaning?
I ask because I was seeing a difference when using a single quoted string vs a double quoted as a object key.
name = "George"
"My Name: #{name}" ====> "My Name: George"
'My Name: #{name}' ====> "My Name: #{name}"
Literal in this case means that it is literally what you wrote in the string
For this reason (and a few others) I like to use a convention of double quotes when the string is natural language that is meaningful to an end user (for example an error message). And single quotes for symbols that are meaningful to the program (like property names, flags, module names, etc).
And no, that's not your fault, the word 'literal' has like 20 definitions in cs.
Related
I always used the following syntax to be sure that variable were expanded in a string:
"my string with a $($variable)"
I recently ran into the following syntax:
"my string with a ${variable}"
Are they equivalent? Any difference?
To complement marsze's helpful answer:
${...} (enclosing the variable name in { and }) is indeed always necessary if a variable name contains special characters, such as spaces, ., or -.
Not special are _ and - surprisingly and problematically - ?.
Note: : is invariably interpreted as terminating a PowerShell drive reference, in the context of namespace variable notation, or a scope specifier, irrespective of whether {...} enclosure is used or required (e.g., in $env:USERNAME or ${env:USERNAME}, env refers to the PowerShell drive representing all environment variables; in $script:foo or ${script:foo}, script refers to the script's scope and its variables).
Note:
${...} - the syntax for disambiguating a variable name - is not to be confused with $(...), which is the subexpression operator, needed to embed any expression or command that goes beyond a stand-alone variable reference in an expandable string ("..."). As such, the two syntax forms are independent of one another and may need to be combined in a given situation; e.g. "$var" / "${var}" work fine, but "$var.someProperty" / "${var}.someProperty" do not: you need "$($var.someProperty)" / "$(${var}.someProperty)"
In the context of string expansion (interpolation) inside "...", there is another reason to use ${...}, even if the variable name itself doesn't need it:
If you need to delineate the variable name from directly following non-whitespace characters, notably including ::
$foo = 'bar' # example variable
# INCORRECT: PowerShell assumes that the variable name is 'foobarian', not 'foo'
PS> "A $foobarian."
A . # Variable $foobarian doesn't exist -> reference expanded to empty string.
# CORRECT: Use {...} to delineate the variable name:
PS> "A ${foo}barian."
A barbarian.
# INCORRECT: PowerShell assumes that 'foo:' is a *namespace* (drive) reference
# (such as 'env:' in $env:PATH) and FAILS:
PS> "$foo: bar"
Variable reference is not valid. ':' was not followed by a valid variable name character.
Consider using ${} to delimit the name.
# CORRECT: Use {...} to delineate the variable name:
PS> "${foo}: bar"
bar: bar
See this answer for a comprehensive overview of PowerShell string-expansion rules.
Note that you need the same technique when string expansion is implicitly applied, in the context of passing an unquoted argument to a command; e.g.:
# INCORRECT: The argument is treated as if it were enclosed in "...",
# so the same rules apply.
Write-Output $foo:/bar
# CORRECT
Write-Output ${foo}:/bar
Finally, a somewhat obscure alternative is to `-escape the first character after the variable name, but the problem is that this only works as expected with characters that aren't part of escape sequences (see about_Special_Characters):
# OK: because `: is not an escape sequence.
PS> "$foo`: bar"
bar: bar
# NOT OK, because `b is the escape sequence for a backspace character.
PS> "$foo`bar"
baar # The `b "ate" the trailing 'r' of the variable value
# and only "ar" was the literal part.
${variable} is the syntax for variable names that include special characters.
(See about_Variables -> Variable names that include special characters
)
Example:
${var with spaces} = "value"
"var with spaces: ${var with spaces}"
So in your case it's basically the same as simply writing $variable
Note that $() is helpful for json objects:
"My json property is $($jsonObj.property)"
I want to insert a string that contains double quotes and single quotes as below.
db.collectionName.insert({"filedName" : "my field contains "double quotes" and 'single quotes' how to insert"}) ;
When I try insert above, it got error as my field contain double quotes, can some one tell me something like escape sequence to insert double quote?
Can't do as under my field also contain single quotes.
db.collectionName.insert({"filedName" : 'my field contains "double quotes" and 'single quotes' how to insert'}) ;
I think it depends on which context you use your code.
If it's in pure js (node.js for example) you can escape the quote char with \, like this :
db.collectionName.insert({"filedName" : "my field contains \"double quotes\" and 'single quotes' how to insert"}) ;
But in the HTML context it's not possible, you need to replace the double-quote with the proper XML entity representation, "
Consider using grave/accent (`, decimal ASCII code 96) for string enclosing quotes.
JSON allows unicode syntax using \u1234 format according to ECMA-404. Therefore you can use the following syntax to insert double quote and single quotes from MongoDB shell.
db.collectionName.insert({"filedName" : "my field contains \u0022double quotes\u0022 and \u0027single quotes\u0027 how to insert"})
Further, you can use this syntax to insert non-ASCII characters too. This special handling is required if we are forming the JSON manually. If the JSON is being serialized automatically from plain objects (e.g. POJOs) using a framework such as GSON, Xstream the required conversion would happen automatically while converting to JSON.
Please could anyone explain me why the following happens:
"Fancy string - Hor""ray"
# outputs correctly (only one double quote): Fancy string - Hor"ray
'Hor"ray'.Replace('"', '""')
# outputs correctly (two double quotes): Hor""ray
"Fancy string - $('Hor"ray'.Replace('"', '"'+'"'))"
#outputs correctly (two double quotes): Hor""ray
"Fancy string - $('Hor"ray'.Replace('"', '""'))"
# outputs INCORRECTLY (only one double quote): Fancy string - Hor"ray
In my opinion, developers would intuitively expect, that within "$(inline expressions)" Powershell would treat text as statements and won't interfere with the last argument of Replace('"', '""') converting it into '"' (unless the statement interpreter decides to do so).
Do I miss something here?
This appears to be a bug in how PowerShell parses expandable string literals.
From §2.3.5.2 on string literals in the PowerShell 3.0 Language Specification, the expandable-string-literal explicitly rejects the $( sequence so that sub-expression parsing will occur instead.
So it seems reasonable to expect $('""') to parse consistently, whether or not it happens to be embedded in a string literal. And clearly sub-expressions are parsed separately, since they support values that would be illegal on their own in an expandable string (e.g. you can write "$('"')" or "$('`""')", where " '"' " or " '`""' " would fail).
However, comparing the AST from [Management.Automation.Language.Parser]::ParseInput for both $('""') and "$('""')", we get two different results. Both have a final StringConstantExpressionAst element with an Extent of '""', but the Value for the stand-alone sub-expression is "" while the Value for the embedded sub-expression is ".
Its because the inline expression is evaluated and its string value is then placed in the string and evaluated.
#Breaking "Fancy string - $('Hor"ray'.Replace('"', '""'))" down
#This inline expression is evaluated first
$('Hor"ray'.Replace('"', '""'))
#giving
Hor""ray
#That value is then interpreted as part of the string
"Fancy string - Hor""ray"
#giving
Fancy string - Hor"ray
This is exactly what I would expect to see. The inline expression evaluated and its resulting value then being used.
Could this not be done by simply using things like below:
`'$($RemFiles[$i].FullName)`'
`"$($RemFiles[$i].FullName)`"
Use the backtick and either a single or double quote to then prevent powershell from using this as an open comment, thus putting the actual symbol in...
The above outputs:
'F:\portable\adobe'
or
"F:\portable\adobe"
I noticed that it seems you are telling it to literally add two double quotes rather than just using the backtick to force it. Therefore telling it to add nothing surely :S So could you change this to something like this:
"Fancy string - $('Hor"ray'.Replace('"', '`"`"'))"
Though that may make 3, as you have one present in Hor"ray anyway.
Just got to test it, was busy with something:
PS D:\> "Fancy string - $('Hor"ray'.Replace('"', '`"`"'))"
Fancy string - Hor""ray
Scroll down on the site below to find out about the backtick and how/where it can be used.
http://www.neolisk.com/techblog/powershell-specialcharactersandtokens
From strings blog post :
Some people think Go strings are always UTF-8, but they are not: only
string literals are UTF-8. As we showed in the previous section,
string values can contain arbitrary bytes; as we showed in this one,
string literals always contain UTF-8 text as long as they have no
byte-level escapes.
To summarize, strings can contain arbitrary bytes, but when
constructed from string literals, those bytes are (almost always)
UTF-8.
Can you give me an example of a string literal that isn’t an utf-8 ?
What is the difference in go between "string literal" , "string value" , "string literal without byte-level escapes" .
Hope this helps:
As 32bitkid mentioned: The following character in Go source code is a string literal whose value is not UTF-8 encoded: "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98".
The idea of a "string literal" exists in Go source code only and has no representation in a compiled or even running program. A string literal in Go source code is written as "cat dog" and if your string literal needs to contain something your keyboard is missing (or your editor cannot display) you may use "byte level escapes" like this "cat\x07dog". Once your Go source code is compiled the notion of a string literal vanishes: There are only strings and they have some value. This value may be computed during the running time of your code or consist of values generated from "string literals" in your source.
"String literals" are to strings what "number literals" ar to ints: "abc" is a string literal and 20 is an int literal. Both may have different representations, e.g. "\x61bc" and 0x14. But once your code is compiled there is no difference whether your int value came from the literal 20 or 0x14. Same with strings. Only complication: Go source code is UTF-8 allways.
In scala, "here docs" is begin and end in 3 "
val str = """Hi,everyone"""
But what if the string contains the """? How to output Hi,"""everyone?
Since unicode escaping via \u0022 in multi-line string literals won’t help you, because they would be evaluated as the very same three quotes, your only chance is to concatenate like so:
"""Hi, """+"""""""""+"""everyone"""
The good thing is, that the scala compiler is smart enough to fix this and thus it will make one single string out of it when compiling.
At least, that’s what scala -print says.
object o {
val s = """Hi, """+"""""""""+"""everyone"""
val t = "Hi, \"\"\"everyone"
}
and using scala -print →
Main$$anon$1$o.this.s = "Hi, """everyone";
Main$$anon$1$o.this.t = "Hi, """everyone";
Note however, that you can’t input it that way. The format which scala -print outputs seems to be for internal usage only.
Still, there might be some easier, more straightforward way of doing this.
It's a totally hack that I posted on a similar question, but it works here too: use Scala's XML structures as an intermediate format.
val str = <a>Hi,"""everyone</a> text
This will give you a string with three double quotation marks.
you can't
scala heredocs are raw strings and don't use any escape codes
if you need tripple quotes in a string use string-concatenation add them
You can't using the triple quotes, as far as I know. In the spec, section 1.3.5, states:
A multi-line string literal is a sequence of characters enclosed in triple quotes
""" ... """. The sequence of characters is arbitrary, except that it may contain
three or more consuctive quote characters only at the very end. Characters must
not necessarily be printable; newlines or other control characters are also permitted.
Unicode escapes work as everywhere else, but none of the escape sequences in
(§1.3.6) is interpreted.
So if you want to output three quotes in a string, you can still use the single quote string with escaping:
scala> val s = "Hi, \"\"\"everyone"
s: java.lang.String = Hi, """everyone