Module:String: Difference between revisions

From HorizonXI Wiki
(join: non-empty arguments only)
(add unescape function)
 
Line 5: Line 5:
]]
]]


local str = {}
local p = {}


--[[
--[[
Line 16: Line 16:
]]
]]


function str.join(frame)
function p.join(frame)
     local separator = frame.args[1]
     local separator = frame.args[1]
     local parts = {}
     local parts = {}
Line 29: Line 29:
end
end


return str
--[[
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

Latest revision as of 16:43, 6 October 2025

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&#39;s Paeon}}
]]

local html_entities = {
    ["&amp;"] = "&",
    ["&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