Removing specific character from string?

For some reason when I do string.gsub it doesnt remove teh specific character.

local text = wall.ProximityPrompt.ActionText -- "$150"
local price = tonumber(string.gsub(text,"$","")) -- Print: "$150 1"

“$” is a string pattern. If you put a percent sign before it, you’re indicating you don’t want it to be detected as a string pattern but as the character itself. So:

local price = tonumber(string.gsub(text, "%$", ""))

Doesn’t work, still the same error: invalid argument #2 to ‘tonumber’ (base out of range)

That’s because string.gsub returns a second value, which is the number of substitutions made. tonumber also accepts a second parameter, which is the base the number is in. You should run each function separately.

local priceAsString, _subs = string.gsub(text, "%$", "")
local price = tonumber(priceAsString, 10)

Welp, i have tested this code which i wrote with text = “$150” and it works for me:

local text = "$150" -- "$150"
local cleanedText = string.gsub(text, "%$", "") -- Remove the dollar sign (returns 150 and 1 but we save only 150)
local price = tonumber(cleanedText) -- Convert the cleaned string to a number

print(cleanedText) -- Should print: 150
print(price) -- Should print: 150

-- You can do it like this too:
local cleanedText = string.match(text, "%d+") -- Extract only the numeric part
local price = tonumber(cleanedText) -- Convert the cleaned string to a number

print(cleanedText) -- Should print: 150
print(price) -- Should print: 150

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.