String replace in chat

Hello, I’m trying to replace a message for example, the player says “i like tacos” and I want to remplace tacos with quesadilla and the message will be sent like this “i like quesadilla”, how I can do this I’ve been trying with this…

if msg:find("tacos") then msg = msg:gsub("tacos","quesadilla") end

but it doesn’t works.

local message = "i like tacos"
local message2 = "i did not"

print(message:gsub("tacos", "quesadilla")) --> i like quesadilla 1
print(message2:gsub("tacos", "quesadilla")) --> i did not 0

You don’t need to necessarily have the find statement in there.


Here’s another way you can do it by using string.find if you prefer this instead, plus it won’t have a number at the end of it.

local Message = "i like tacos"
local St, En = string.find(Message,"tacos")
if St then
    -- Outputs "I like quesadilla"

Edit: Forgot gsub returned two values so what ExtremeBuilder13 did is the better way compared to what colbert2677 did, but I prefer using string.find.

1 Like

Actually, it’s easy to separate the number from the string. Gsub returns the new string and the matches separately.

local message = "I like tacos"
local s, matches = message:gsub("taco", "quesadilla")

print(s) -- prints "I like quesadillas"

It’s like you said, though, gsub vs find is mostly preference.