Checking if part of a string contains a string in a table

I’m trying to make a word filter that detects if a player’s chat message contains a string that is in the table. (e.g. Message sent in chat: “This is a test message”, Detected word: “test”.) I tried using table.find() to do so.

local filteredWords = {"test", "kgl", "admin"}

game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(msg)
		local loweredText = string.lower(msg)
		if table.find(filteredWords, loweredText) then -- This is the problem
			print("filtered word detected")
		end
	end)
end)

However, it printed only if the message contained the filtered word itself. If other words are added to the message, nothing happens. Is there another method that doesn’t result in this?

Well what are you trying to achieve here then?

When a player sends a chat message, and it contains a word in the filteredWords table, I want print("filtered word detected") to run.

You should split the message into an array of words, and then loop through that array checking if the word exists in the filtered words.

What you’re doing right now is checking if the entire message string is in the filtered words array.

How would I split the message into an array of words?

for _, filteredWord in next, filteredWords, nil do
    if string.find(loweredText, filteredWord) then
        print("Filtered word detected!")
    end
end

Just also bare in mind this will detect parts of words. You could do as @robloxdestroyer1035 said and split it.

local splitMessage = string.split(loweredText, " ")
for _, word in next, splitMessage, nil do
    if table.find(filteredWords, word) then
        print("Filtered word detected!")
    end
end
1 Like

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