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

How to find word used in string from a table and then replaces the words with new one?

How to make a script that finds words used in a string from a table and then replaces the words with new one?

Here's my attempt:

local stringtofind = {'are', 'you'}
local stringtoprocess = 'i think you are cool'
local startvalue,endvalue = string.find(stringtoprocess,stringtofind)
local firststring = string.sub(stringtoprocess,1,startvalue-1)
local secondstring = string.sub(stringtoprocess,endvalue+1,string.len(stringtoprocess))
local stringtoinsert = "you're"
local processedstring = firststring .. stringtoinsert ..secondstring

print(processedstring) -- i want it to print "i think you're cool"

Any help?

2 comments

0

string.gsub(string, thingToReplace, thingToReplaceItWith) should do what you're looking for

0

You can pass dictionaries through gsub

1 answer

✓ Accepted answer

You can pass dictionaries through gsub.

Example code:

local replacers = {
  ["hello"] = "ok",
  ["cool"] = "epic"
}

local old = "hello this is cool"
local new = old:gsub("%S+", replacers)

print(old)
print(new)

Output: >> hello this is cool >> ok this is epic

In this case the string new is old but it replaced all words in the dictionary replacers with each index's value. e.g. "hello" is now "ok" and "cool" is now "epic"

2 comments

0

now this is epic

0

thank you so much

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