Need help on a character replacer

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I made a small code to replace characters such as “<” into “<”. However it doesn’t work correctly as you see in the screenshot below:
    image

Expected output:
image

Code:

local ct = {
	{"<", "&lt; "},
	{">", "&gt; "},
	{[["]], "&quot; "},
	{[[']], "&apos; "},
	{"&", "&amp; "}
}
for _, v in pairs(ct) do
	if not string.find(msg, v[1]) then continue end
	local ss = string.split(msg, v[1])
	local ns = ""
	for _, t in pairs(ss) do
		if ns == "" then
			ns = t..v[2]
		else
			ns = ns..t..v[2]
		end
	end
    msg = ns
end

You have to do the ampersand at the end after everything else. You can either do this manually or switch your pairs loop to an ipairs loop.

You should also use gsub instead of concatenating everything at the end.

I’m unfortunately very unexperienced with string.gsub() so can you please give me an example of doing so?

Sure.

Something like this should work:

local ct = {
	{"<", "&lt; "},
	{">", "&gt; "},
	{[["]], "&quot; "},
	{[[']], "&apos; "},
	{"&", "&amp; "}
}

for i,v in ipairs(ct) do
    msg = string.gsub(msg, v[1], v[2])
end

Seems like it did partially fix it but only now, well uh you can see it for yourself:
image

Expected output:
image

Oh wait, I think you should actually do the ampersand at the beginning, my bad.

Try this:

local ct = {
	{"&", "&amp; "},
	{"<", "&lt; "},
	{">", "&gt; "},
	{[["]], "&quot; "},
	{[[']], "&apos; "},
}

for i,v in ipairs(ct) do
    msg = string.gsub(msg, v[1], v[2])
end
print(msg)
1 Like

That actually fixed it, thank you so much for helping me!

image
image

1 Like