Fix escaping of characters in substitution variables, fixes #17286.
Also use ""+ rather than toString() to allow for null values.