How can I add double quote characters to a given string?
local str = "foo"
How can I get the string "foo"
where the string contains a leading and trailing quote "
?
You can just glue the quote to the string:
local str = "foo"
print('"' .. foo .. '"') --> "foo"
print("\"" .. foo .. "\"") --> "foo"
print([["]] .. foo .. [["]]) --> "foo"
But if you're constructing data for machine consumption (e.g. for serialization), you want to escape quotes and other funny characters that may be inside the string. Use "%q"
format specifier for this:
local str = 'f"o"o'
print(string.format("%q", str)) --> "f\"o\"o"
In shorter form:
print(("%q"):format(str)) --> "f\"o\"o"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With