What is the difference between single and double quoted strings?
Is there a way to get a variable expanded inside a string, or do they always need to be joined like: 'Hello, ' . s:name . '!'
The only difference between single and double quoted string is related to backslash. To display special characters like newline, bells, tabs, etc, you need to use double-quotes -> "\n"
.
Within a single-quoted string, '\'
is itself => '\n'
is a two-characters string (a backslash + n
). Within double quotes, you have to double it -> "\\"
, which makes them un-practical to define regexes.
Regarding string expansion, you have a few choices:
'Hello, ' . s:name . '!'
join(['Hello, ', s:name, '!'], '')
-- which we never useprintf('Hello %s!', s:name)
lh#fmt#printf('Hello %1!', s:name)
-- from lh-vim-lib, when we don't want to know about types, and when we don't need to format fields, but when we want to use formats like: 'Hello %1. How are you doing %1 this %2
'.'
inside a single-quoted string?
'foo''bar'
, or use both kind of quotes: 'foo'."'".'bar'
Commented
Sep 28, 2016 at 7:40
In the Vim documentation a double quoted string and a single quoted string are both referred to as a string constant
.
:help expr-string
:help literal-string
The help lists the difference for single quotes as:
This string is taken as it is. No backslashes are removed or have a special meaning. The only exception is that two quotes stand for one quote.
Because I'm a Javascript developer I see quite a lot of similarity with the single and double quoted strings there - but obviously string contactenation is done with .
in Vimscript.
Further information from Learn Vimscript the Hard Way - Strings that has the default kind of string is a double quoted strings with a special section for Literal Strings
Vim also lets you use "literal strings" to avoid excessive use of escape sequences.
...
We'll revisit literal strings when they become most useful, later in the book (when we dive into regular expressions).