How to improve my Python string.strip function

So I wrote a strip function like python, where it removes leading and trailing whitespaces, as well as the optional chars argument.

function string_ext.strip(s, chars) -- Strips leading and trailing whitespace, as well as characters specified by the chars string
	return (s:gsub("^%s+", ""):gsub("%s+$", ""):gsub(chars and string.format("[%s]", chars) or "", ""))

It works perfect, but I don’t like how I have chained gsub calls. I feel like I could do it in one call, but am unsure of a pattern to use.

print(string.gsub("  Hello World  ","^%s*(.*)%s*$", "%1"))

As described on this page, you can make captures inside your pattern. I’m sure you can work out how to remove trailing provided chars in the same gsub call.

Note that if you chain them in order, selected characters on the edge might leave trailing whitespace after their removal. Also, the current implementation seems to remove all provided chars and not just trailing ones. Nice work though, this function makes a nice addition to anyones library.

Good luck!