Replacing a certain formatting code

Is there a way to replace a certain color code, for example &a, while just leaving the other color codes intact?
The usecase is, I want to give players a permission to use a certain color in chat. So if they have the permission for the green color code they can use the green color, but can’t use any other colors.

So that will change
&fHey &ahey &3hey
to
&fHey (green)hey &3hey(/green)

An alternative way I can think of is deserialising the whole formatted text to a Text object, then iterating over all children(and their children, recursively) and resetting the ‘illegal’ colors to the color of the child before this one. Doing it this way has the effect of removing illegal colors/styles formatting codes, whereas your idea leaves the illegal ones visible.

Very simply:

TextSerializers.LEGACY_FORMATTING_CODE.deserialize(str.replace("&3", "§3"));
3 Likes

Oh that is pretty smart, thanks

Is there a way to do this on a Text instead of on a String, without converting it to plain thus losing click actions etc?

You could do what @RandomByte suggested and iterate over the tree and rebuild, replacing as you go through

2 Likes