Escaping Rich Text

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('[&<>"\']',{
		['&'] = '&amp;',
		['<'] = '&lt;',
		['>'] = '&gt;',
		['"'] = '&quot;',
		['\''] = '&apos;',
	})
end

This function uses the gsub method to replace characters with their corresponding HTML escape codes. For example, it turns & into &amp;, < into &lt;, 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>`)

9 Likes

Is this sure to when i edit an Minecraft text ,text stop formatting until i finish and they reformat again?

1 Like

In this case, user input is stored as text in a variable. While you are typing, the text can be displayed in its escaped version to prevent any unwanted formatting while editing. Once you’re finished editing, the text can be rendered as intended (with rich text formatting applied).

How to when i write on a text box ,reveals their formats and finished ,activate the formats ,I need § to do it

One simple way of doing that is turning rich text off while the text is being edited.

-- Place this script in StarterPlayerScripts

local PlayersService = game:GetService('Players')
local player = PlayersService.LocalPlayer

local gui = Instance.new('ScreenGui',player.PlayerGui)

local textBox = Instance.new('TextBox',gui)
textBox.Size = UDim2.fromOffset(500,200)
textBox.ClearTextOnFocus = false

textBox.Focused:Connect(function()
	textBox.RichText = false
end)

textBox.FocusLost:Connect(function()
	textBox.RichText = true
end)

You won’t need the escape function here as disabling rich text completely is enough in your use case.