Module:String: Difference between revisions
From Horizon Wiki Mirror
Content deleted Content added
imported>Kaimoon0 m return |
imported>Kaimoon0 add unescape function |
||
| (One intermediate revision by the same user not shown) | |||
| Line 5: | Line 5: | ||
]] |
]] |
||
local |
local p = {} |
||
--[[ |
--[[ |
||
join |
join |
||
Using the first argument as a separator, join the remaining |
Using the first argument as a separator, join the remaining non-empty arguments |
||
together. |
|||
Example: |
Example: |
||
{{#invoke:String|join|,|apples|bananas|cherries}} |
{{#invoke:String|join|,|apples|bananas|cherries}} |
||
]] |
]] |
||
function |
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 |
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 = { |
|||
["&"] = "&", |
|||
["<"] = "<", |
|||
[">"] = ">" |
|||
} |
|||
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 |
|||
| ⚫ | |||
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's Paeon}}
]]
local html_entities = {
["&"] = "&",
["<"] = "<",
[">"] = ">"
}
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