How to ensure a plain text string when using rich text field

Is there a way to extract the plain text from a string that potentially contains rich text format characters?

We have a custom character name display where I want to use rich text for our OWN use. But to prevent users from entering in rich text formatting, I’d like to filter their name entry to ensure there is no rich text markup.

I realized as I write this… I guess the proper way is to escape any rich-text markup from the user entered string. Does anyone know if such a method exists already? If not, I suppose I could role my own without too much effort.

You need to remove all “<…>” from text.

function RichTextToNormalText(str:string)
    local output_string = str
    while true do 
        if not output_string:find("<") and not output_string:find(">") then break end -- If not found  any <...>
        if (output_string:find("<") and not output_string:find(">")) or (output_string:find(">") and not output_string:find("<")) then return error("Invalid RichText") end -- if found only "<..." or "...>"
        output_string = output_string:gsub(output_string:sub(output_string:find("<"),output_string:find(">")),"",1) -- Removing this "<...>"
        task.wait()
    end
    return output_string
end
2 Likes

Thanks, I was thinking along those lines initially, but realized it might be better to use escape codes.

For instance, if user wanted their name to be "<Coolio>" then I should really convert it to "&lt;Coolio&gt;" based on the escapes listed here:

https://developer.roblox.com/en-us/articles/gui-rich-text

In case anyone wants something like this, here’s the code I’m using:

function stringEscapeRichText( s )
	s = string.gsub( s, "&",  "&amp;" ) -- (must do & first)
	s = string.gsub( s, "<",  "&lt;" )
	s = string.gsub( s, ">",  "&gt;" )
	s = string.gsub( s, "\"", "&quot;" )
	s = string.gsub( s, "'",  "&apos;" )
	return s
end

3 Likes