Removing consecutive spaces from strings

I want to remove consecutive spaces of any length from a string. Example:

“Hello my name is rokedev, how do you do today?” → “Hello my name is rokedev, how do you do today?”

I’ve tried a number of things including using string.match, string.gsub, etc but I’m fairly inexperienced in string manipulation at this level

As I said I tried a few of the string functions that I’m relatively new to, recieving very little success, either not removing the spaces or removing all of the spaces.

I searched throughout the DevForum and even outside of Roblox/Lua and I found some threads with functions that aren’t available in Roblox.

I’d like any help to set me in the right direction, Thanks!

Screenshot_4

(A screenshot of what the example was meant to look like)

You can use string.gsub alongside the %s pattern to achieve this. If you want to get fancy, you can even throw in some capture magic.

The simple version: string.gsub('%s+', ' ')
This will replace all substrings of one or more whitespaces in your string with a single space character. %s refers to whitespace (space, tab, newline), and + makes it greedy and consumes at least 1 character.

The slightly more interesting version: string.gsub('(%s)%s*', '%1')
This captures one whitespace character, and consumes 0 or more whitespaces after it. But, instead of replacing your capture with a single normal space, it does so with the first space character it found. So it won’t turn a bunch of tabs into a space, and instead into a single tab.
It works because captures (()) can be referred to by %n, where n is the capture index.

9 Likes

I tested it and it works flawlessly, Thanks!