Module:String

From HorizonXI Wiki

Documentation for this module may be created at Module:String/doc

--[[

A module for general string functions.

]]

local p = {}

--[[
join

Using the first argument as a separator, join the remaining non-empty arguments
together.
Example:
{{#invoke:String|join|,|apples|bananas|cherries}}
]]

function p.join(frame)
    local separator = frame.args[1]
    local parts = {}

    for k, v in ipairs(frame.args) do
        if k > 1 and v ~= '' then
            table.insert(parts, v)
        end
    end

    return table.concat(parts, separator)
end

--[[
unescape

Takes the string given as an argument, and converts HTML escape codes back
to printable characters.
Example:
{{#invoke:String|unescape|Army's Paeon}}
]]

local html_entities = {
    ["&"] = "&",
    ["&lt;"]  = "<",
    ["&gt;"]  = ">"
}

function p.unescape(frame)
    local s = frame.args[1]

    -- numeric decimal
    s = mw.ustring.gsub(s, "&#(%d+);", function(n)
        return mw.ustring.char(tonumber(n))
    end)

    -- numeric hex
    s = mw.ustring.gsub(s, "&#x([%da-fA-F]+);", function(n)
        return mw.ustring.char(tonumber(n, 16))
    end)

    -- named entities
    for k, v in pairs(html_entities) do
        s = s:gsub(k, v)
    end

    return s

end

return p