Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use string.gsub correctly?

I have a string that has the value of a player's name. It was in a table and I converted it correctly using the JSONEncode() function (which is 100% correct). There are two symbols that are left over from the conversion - these square brackets [ ]. I'm trying to use string.gsub to remove them, but it's not working.

Help would be appreciated asap (:

Here is the code below for what I've tried to do with string.gsub:

local finNames = string.gsub(json,'%[', "")
local finXames = string.gsub(finnames,'%]',"")
print(finXames)

1 answer

✓ Accepted answer

Use JSONDecode() to convert JSON back into a lua table again. Do not bother trying to parse JSON yourself.

Though you should definitely not do this to parse JSON, here's how you would use gsub:

string.gsub(s, pattern, replace)
--for example
print(string.gsub("This is a string!", "string!", "gsub'd string!"))
--returns and prints "This is a gsub'd string!"
print(string.gsub("[This is a string!]", "%[", ""))
--returns and prints "This is a string!]"

2 comments

0

I managed to get it working with the JSONEncode ( ) as well. Why not try and use it? (I've accepted your answer as it is helpful, thank you!)

0

Thanks as well. You're supposed to use both, JSONEncode for encoding JSON, and then JSONDecode for decoding JSON. Both are very useful for converting between formats. It's impractical to write your own parser because it won't work for all datatypes unless you make it, and Roblox already offers JSONDecode for free. Plus, it's probably faster to use the native function.

This discussion is preserved as it was. New answers, comments, and votes are closed.