How to trim just the spaces on the end from a string

I’m trying to trim off any spaces on the front and end of a string. I know that in javascript you can use String.trim(str), but I don’t think you can do that in studio. Is there any way to do this?

P. S. I also know that you can use

string.gsub(str, " ", "")

But that removes all spaces, not just ones at the front and back.


1 Like

I’m pretty sure I misunderstood your post, but if you’re talking about removing spaces before and after a string, this might work.

local str = " string string "
string.sub(str, 2, #str-1)

Hmm, ok. The thing is it only removes the first space from the front or end, and not any others. It’s probably fine for what I need though.

local function trim(str)
    return string.gsub(str, "^%s*(.-)%s*$", "%1")

print("/" .. trim("  \t jello  \n \t ") .. "/") --> /jello/

From string - Lua trailing space removal - Stack Overflow