Hey!
When working with rich text in Roblox, special characters like <
, >
, &
, "
, and '
need to be escaped to avoid being interpreted as part of the markup tags. You can use a simple function to handle this process, ensuring your text displays correctly and prevents any parsing errors.
function escape(text:string)
return text:gsub('[&<>"\']',{
['&'] = '&',
['<'] = '<',
['>'] = '>',
['"'] = '"',
['\''] = ''',
})
end
This function uses the gsub method to replace characters with their corresponding HTML escape codes. For example, it turns &
into &
, <
into <
, and so on. By using this function, you can display text containing these characters without breaking the rich text formatting.
This is especially useful when you are dealing with user-generated content, where such characters might appear in the input text. Escaping them ensures your text renders correctly, even when rich text tags are present.
Let’s assume we have user-generated text
text = 'I am cool! <'
and want to output it. Here, the escape
function becomes essential when dealing with special characters like <
in the string. Without escaping, the <
character will be interpreted as the start of a rich text tag, causing unwanted formatting:
print(`quinacon: <font color="#ff0000">{text}</font>`)
If we instead use our escape function, we can prevent this and correctly render the text:
print(`quinacon: <font color="#ff0000">{escape(text)}</font>`)