How to Left Trim (or Right Trim) a string?

I want to remove the spaces only from the left of a string.
If I try this:

a = string.gsub("  abc   ", "%s+", "")
print('/'.. a ..'/')

ā€¦ it will remove the spaces also from the right:

/abc/

Is there another way to remove only the left spaces (using gsub)?

1 Like

nvm, I solved it with 3 lines:

while string.sub(Text, 1, 1) == ' ' do -- trim left spaces
	Text = string.sub(Text, 2)
end

You can use the carot character ā€˜^ā€™ to anchor a search pattern to the start of a string.
Similarly the dollar sign ā€˜$ā€™ can be used to anchor a search pattern to the end of a string.

local s = "  abc   "
s = string.gsub(s, "^%s+", "")
print("'"..s.."'") --'abc   '
5 Likes
^%s+ -- Left Trim
%s+$ -- Right Trim
%s+ -- Trim

Thank you. :+1:t2:

3 Likes