RichText coloring with variables

Hey there!
So I’m trying to color a TextLabel with each letter having a different color. The problem is that I need to do it with variables and it just doesn’t work.

word.Text = “<font color = ‘#00be00’.>”…Variable1…“</font.><font color = ‘#ff0000’.>”…Variable2

(I know there are dots that are missplaced and there are 3 dots instead of 2, that’s because the formatting doesn’t let me show the code without it)

Any help would be really appreciated!

5 Likes

You can do this:

local Variable1 = "put something here"
local Variable2 = "put something here"

word.Text = '<font color = "#00be00">' .. text .. '</font><font color = "#ff0000">' .. Variable2

Use single quotes when the string itself contains double quotes.

1 Like

If you want to avoid dealing with this mess, you could use string.format

local richTextFormat = '<font color="#00be00">%s</font><font color="#ff0000">%s</font>'
word.Text = string.format(richTextFormat, "word 1", "word 2")

Sadly, this only works if the variables I put are strings.

This doesn’t work:

local Variable1 = string.sub(word.Text, 1, count - 1)
local Variable2 = string.sub(word.Text, errorIndex, count)

word.Text = '<font color = "#00be00">' .. Variable1 .. '</font><font color = "#ff0000">' .. Variable2 .. '</font>'

This solution doesn’t work with what I said

The same goes to this solution

No, the text is just not formatted. It shows the format itself as text.

image_2021-05-01_123751
It seems like there is no issue. Did you enable RichText on the label?

Yes, you aren’t using what I sent tho.

Instead of concatenating the variables, I used string.format

local richTextFormat = '<font color="#00be00">%s</font><font color="#ff0000">%s</font>'

word.Text = string.format(richTextFormat, Variable1, Variable2)

With these variables it doesn’t work tho:

local Variable1 = string.sub(word.Text, 1, count - 1)
local Variable2 = string.sub(word.Text, arrorIndex, count)

Could you print that variables?

You might want to use word.Content instead of word.Text, if you want to exclude the xml tags.

edit: image_2021-05-01_125523 :sweat_smile:

Actually, yes, I can print them.

This just gives me: “Content is not a valid member of TextLabel”

Print them, so I can check them.

This is what it prints:
- Client
< - Client

I think it prints this because the text is weird because of the formatting.

Okay I got it worked out. Thank you for your help!