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

How to subtract a word from a string?

Example:

I have a string: "Noobs RULE" and I want to remove " RULE" from it, so it turns into "Noobs". How can I do that in Lua?

1 answer

✓ Accepted answer

You can use gsub to replace all substrings with something else. In this case it could be

str = str:gsub(" RULE", "");

Alternatively, if you just knew you wanted the first 5 characters ("Noobs"), you could just use sub:

str = str:sub(1, 5);

You could also take advantage of Lua's pattern matching and remove the spaces intelligently, though this makes more assumptions than you have stated:

str = " " .. str .. " ";
-- Pad with spaces

str = str:gsub("%s+RULE%s+", " ")
	:gsub("%s+RULE%s*", " ")
	:gsub("%s*RULE%s+", " ");
-- Replace [a]RULE[b] with a single space,
-- where [a] and [b] together are only space characters and
-- at least one space character.

str = str:gsub("^%s*(.-)%s*$", "%1");
-- Trim any extra space at the beginning or end of
-- the string (since we added some initially to make
-- the middle step work with first / last words)

2 comments

0

Thanks a lot, I love ya.

0

I just fixed a typo in the last example, so if you were using that, check it!

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