Basic help for string.gsub

Hello, I’m having a difficulty using the string.gsub is wanted to know how to get all the strings, here’s an example:

local String = 'LocalPlayer localplayer LoCALPlayeR'
print(string.gsub(String, 'LocalPlayer', 'LocalPlayer'))
-- Result: LocalPlayer localplayer LoCALPlayeR 1

I tried to use string.gsub (String, string.lower ('LocalPlayer'), 'LocalPlayer'), but it only get all localplayer.
I wanted to get all LocalPlayer, how to get it?

2 Likes

Your wording poses confusion. What exactly do you want to do? Are you trying to change every account of “LocalPlayer” to use proper capitalisation or are you attempting to get every instance of LocalPlayer present in the string?

string.gsub does not get anything. It returns a string where whatever you found as the “pattern” (second argument) in the string (first argument) it would replace the pattern with whatever is in the third argument (third argument). It also returns how many patterns it found within the string too.

What exactly are you trying to do? What do you mean by “get?”

2 Likes

So from what I’m getting at, you want all forms of capitalized versions of your pattern to be included? That’s simple, just lower the string.

 print(String:lower():gsub("localplayer","LocalPlayer"))
>> LocalPlayer LocalPlayer LocalPlayer 3

Edit: Basically what this does is it lowers your string so you can search for a single pattern (“localplayer”) and then replace all of the "localplayer"s with “LocalPlayer”

9 Likes

An alternative to the above is to adjust your search argument to use Lua string patterns targeting upper and lower case letters instead of the word you want to replace. Ie. you’d use “[Rr][Oo][Bb][Ll][Oo][Xx]” instead of Roblox if you were looking to replace the word Roblox.

This doesn’t really work if you need the search word to be dynamic, and I recommend you stick with lowercasing the string instead.

1 Like

The only downside to this solution is that now the rest of the string has been made lowercase, even if that was not the intention. Another approach that avoids this problem is to pass a function to gsub:

local String = 'LocalPlayer localplayer LoCALPlayeR CAPITAL WORDS'
print((String:gsub("%w+", function(word)
	if word:lower() == "localplayer" then
		return "LocalPlayer"
	end
end)))
6 Likes

Roblox doesn’t mention anything about running a function through gsub in documentation (not even in the wiki before), so this is really good information. :smiley:

2 Likes

You’ll be surprised to learn, then, that tables are also acceptable substitution arguments. Here’s another valid (yet completely unnecessary) solution using a table with a metatable

local String = 'LocalPlayer localplayer LoCALPlayeR CAPITAL WORDS'

print((String:gsub("%w+", setmetatable({}, {__index = function(t, k)
	return k:lower() == "localplayer" and "LocalPlayer" or nil
end}))))
13 Likes