C0nw0nk
C0nw0nk

Reputation: 970

Lua how to remove ".html" text from end of string

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

Answers (2)

DarkWiiPlayer
DarkWiiPlayer

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:

  • If bar ends in '.html', remove the last 5 characters and feed that into foo again (to remove any more occurrences)
  • Otherwise, return bar as it is

Benefits:

  • Tail recursive, so it can't overflow the stack even for very long chains '.html'
  • 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

brianolive
brianolive

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

Related Questions