Reputation: 970
So I have a string in Lua and I want to remove all occurances ".html" text of the end of the string
local lol = ".com/url/path/stuff.html"
print(lol)
Output i want :
.com/url/path/stuff
local lol2 = ".com/url/path/stuff.html.html"
print(lol2)
Output i want :
.com/url/path/stuff
Upvotes: 3
Views: 7237
Reputation: 7064
This can easily be done with a tail-recursive function like this:
local function foo(bar)
if bar:find('%.html$') then return foo(bar:sub(1, -5) else return bar end
end
in words:
Benefits:
string.find
is pretty fast when you anchor the search to the end of the string with $
string.sub
is also rather fast compared to, for example, string.gsub
(note that those two do completely different things, despite the similar name).Upvotes: 2
Reputation: 1671
First, you could define a function like this:
function removeHtmlExtensions(s)
return s:gsub("%.html", "")
end
Then:
local lol = ".com/url/path/stuff.html"
local lol2 = ".com/url/path/stuff.html.html"
local path1 = removeHtmlExtensions(lol)
local path2 = removeHtmlExtensions(lol2)
print(path1) -- .com/url/path/stuff
print(path2) -- .com/url/path/stuff
There is a second value returned from the gsub
method that indicates how many times the pattern was matched. It returns, for example, 1
with path1
and 2
with path2
. (Just in case that info is useful to you):
local path2, occurrences = removeHtmlExtensions(lol2)
print(occurrences) -- 2
Upvotes: 4