Replace Text in chat message

Hello. I’m dealing with a Text object, and I need to replace a word with another Text object. Is there any way to do this?

That’s basically what I want to do:

public void onChat(MessageChannelEvent.Chat event){
    Text message = event.getMessage();
    message.replace("word", textObject.onHover()...);
}

The simplest way would be to serialise the text, do the changes there and then deserialize that. Remeber to use event.setMessage() as well.

String text = TextSerializers.YOUR_CHOICE.deserialize(event.getMessage());
text = text.replaceAll("S", "A");
Text newText = TextSerializers.YOUR_CHOICE.serialize(text);

I wrote a Spannable class for LangSwitch that can do that. Benefit would be that you keep TextActions as well. It is heavily inspired by the String-like handling of Andoids Spannable Text-Objects.
It would look something like

Spannable span = Spannable.from(text);

//string as plain text, text can actually be a Text object
span = span.replace(string, text);

Text modified = span.toText();

Since my Spannable class fully implements CharSequence you should be able to operate it pretty much like any String. Be aware though that I didn’t write any unit or integration tests, so errors in formatting might be possible.

I guess @DosMike has the better solution, but i can also offer this hacky one i created once: A replace util function for Sponge's Text · GitHub :smiley: