Quirrel4.41.0

string.escape

Defined in module "string"
from "string" import escape
pure escape(str: string): string

Returns str with backslash, the two quote characters, and every byte that is not printable ASCII replaced by an escape sequence.

Parameters

strstringthe string to escape

Return value

The escaped string. When there is nothing to escape - including when str is empty - str itself comes back unchanged.

Notes

Only three characters get a one-character escape: \ becomes \\, " becomes \", and ' becomes \'. A NUL byte becomes the two characters \0.

Every other byte outside the printable range 32-126 - a tab, a newline, any other control character, a DEL, or a non-ASCII byte - becomes a four-character \xNN hex escape. It does not become the classic C letter escape (\t, \n, \v, \f, \r); older documentation for this function describes those letter forms, but the code path that would produce them never runs, because none of those characters is printable ASCII.

Example

examples/string/escape.nut
from "string" import escape

// backslash and the two quote characters keep a one-letter escape
println("escape(quotes and backslash) =", escape("say \"hi\"\\bye"))

// every other non-printable byte, including a plain tab or newline,
// becomes \xNN, not the classic C \t \n letter form
println("escape(tab and newline) =", escape("a\tb\nc"))

// nothing to escape: the same string comes back
println("escape(\"plain\") == \"plain\" =", escape("plain") == "plain")
println("escape(\"\") == \"\" =", escape("") == "")
Output:
escape(quotes and backslash) = say \"hi\"\\bye
escape(tab and newline) = a\x09b\x0ac
escape("plain") == "plain" = true
escape("") == "" = true

See also

formatFormats fmt with the following arguments, following the syntax of the C printf family, and returns the result as a new string.
stringmodule index