I am working on a text editor, and I am using a textbox. I want to be able to find text that the use writes and replace it with a different word. For example: If a user writes “hello” I want to replace the hello with hello, I tried using string.split and I get every single word. I then use a for loop to loop through the words and see if any of them is hello and then replace. But I don’t know how I would change the text on the textbox itself with this. Here is my script so far:
--To Color use <font color="">TEXT</font>
function SetTextColor(Spliced)
local Text = ""
for i = 1,#Spliced do
Text = Text.." "..Spliced[i]
end
script.Parent.Text = Text
end
local RedText = {
"if"
}
while wait() do
local TextSpliced = string.split(script.Parent.Text," ")
for i = 1,#TextSpliced do
if RedText[TextSpliced[i]] then
TextSpliced[i] = '<font color="#ff005d">'..TextSpliced[i].."</font>"
end
end
SetTextColor(TextSpliced)
end
As @NyrionDev said above, you can use .gsub. You can find a more indepth view Here
gsub stands for “global substitution” and is used in this format (said by the link): (string s, string pattern, variant replacement, number replacements)
This may happen due to magic characters, which you can filter before passing to the gsub:
function filterMagicCharacters(text)
local magic = {"$", "%","^", "*", "(", ")", ".", "[", "]", "+", "-", "?"}
local result = ""
for i = 1, string.len(text) do
local l = string.sub(text, i, i)
if table.find(magic, l) then
l = "%"..l
end
result ..= l
end
return result
end
print(filterMagicCharacters("[]test")) --%[%]test
--pass this to the gsub
It still does the thing though. It assumes that the “if” inside the <font color="colorValue">if</font> is the if it is looking for. For testing, I replaced “if” with amogus. Here is a video:
Every time you update the text use script.Parent.ContentText as the starting value(instead of script.Parent.Text which also contains the richtext tags).
Nope, that didn’t work. Before using gsub, is there a way I can see if the text is already replaced? Like seeing if there are richtext tags around it? Also, is there a way to only show the reformatted text instead of showing the richtext tags when writing? So that nobody breaks the script?