How would I replace a certain word in a TextLabel?

What the text should say:
“Change announcement Colours…”
What the text says:
“Ch…nge announcement Colours[Player]”

I am trying to understand string.gsub and I found this code and edited it for my own example, before the game is run the text says: “Change announcement Colours[Player]” and once the game is run I require player to be substituted with “…” and later intend on using this knowledge to create a system that changes [player] to the LocalPlayer Name. What has gone wrong here? Any help is appreciated, thank you.

local TextLabel = script.Parent.Text
	local stringtoprocess = TextLabel..""
local stringtofind = "[Player]"

local startvalue,endvalue = string.find(stringtoprocess,stringtofind)

local firststring = string.sub(stringtoprocess,1,startvalue-1)
local secondstring = string.sub(stringtoprocess,endvalue+1,string.len(stringtoprocess))
local stringtoinsert = "..."
local processedstring = firststring..stringtoinsert ..secondstring 
script.Parent.Text = processedstring
2 Likes

String.gsub would probably be best in this instance

local str = "Hello There [Player]"
local str2 = str:gsub("[Player]",game.Players.LocalPlayer.Name)
print(str2)
4 Likes

How would I apply this so it will replace [Player] with the game.players.LocalPlayer.Name) whilst keeping the rest of the text?
I’m assuming I stop the repetition of the string with a debounce.

1 Like

The issue is that [ and ] are magic characters.

Escape them or use the fourth argument of string.find to fix the problem.

[Player] would become %[Player%] for what you’re trying to find.

local stringtoprocess = script.Parent.Text
local stringtofind = "%[Player%]"
local startvalue,endvalue = string.find(stringtoprocess,stringtofind)
local firststring = string.sub(stringtoprocess,1,startvalue-1)
local secondstring = string.sub(stringtoprocess,endvalue+1,#stringtoprocess)
local stringtoinsert = "..."
local processedstring = firststring..stringtoinsert ..secondstring 
script.Parent.Text = processedstring
3 Likes

This is working! Thank you for the help, greatly appreciated.
God such a stupid error on my behalf

1 Like

Out of curiosity; what’s the difference between escaping with % and \? Regex is something I’ve never quite gotten the hang of or understood very much.

Escaping with \?
image
Normal slash makes it work but it isn’t like using a %
image
edit:
image
actual backslash looks like it acts similarly to /

1 Like

I think where I get that preception from is escaping quotes in strings.

local qInQ = "Hello, \"world\"!"

I was wondering if backslash could also work for escaping and why it’s explicitly the percentage sign.