Module:LinkParser
Appearance
Documentation for this module may be created at Module:LinkParser/doc
-- Module:LinkParser
-- Parses links inserted by editors in templates, strips them of the protocol part, leading "www.", and any trailing "/", while otherwise printing exactly what was entered to minimize spoofing.
local p = {}
-- Cache for previously processed URLs (persists during a single page render)
local stripCache = {}
----------------------------------
-- Remove protocol, leading www., and trailing /
----------------------------------
function p.strip(link)
-- Input validation
if not link or link == "" then
return link
end
-- Check cache first for previously processed URLs
if stripCache[link] then
return stripCache[link]
end
-- Combine all operations into a single chain to reduce string allocations
local result = link:gsub("^%a+://", ""):gsub("^www%.", ""):gsub("/$", "")
-- Cache the result before returning
stripCache[link] = result
return result
end
----------------------------------
-- Return a MediaWiki link with:
-- [ originalURL strippedDisplayText ]
----------------------------------
function p.render(frame)
-- Input validation
if not frame or not frame.getParent then
return ""
end
local parent = frame:getParent()
if not parent or not parent.args then
return ""
end
local args = parent.args
local rawLink = args["link"] or ""
-- Early return for empty links
if not rawLink or rawLink == "" then
return ""
end
-- Strip protocol, leading 'www.', and trailing '/'
local displayText = p.strip(rawLink)
-- Construct an external link of the form:
-- [ rawLink displayText ]
return string.format("[%s %s]", rawLink, displayText)
end
return p