Module:String
Documentation for this module may be created at Module:String/doc
-- This module has been copied from: https://dev.fandom.com/wiki/Module:String
-- It is available under: "Except where otherwise permitted, the text on Fandom communities (known as “wikis”) is licensed under the
-- Creative Commons Attribution-Share Alike License 3.0 (Unported) (CC BY-SA)."
-- license: https://www.fandom.com/licensing
--- Return delimited string piece, like PHP's `explode()`.
-- Indexing is **0-based** to match the behavior of `{{#explode}}`
-- parser function.
--
-- @function str.explode
-- @param {table} frame Invocation frame object.
-- @param {table} frame.args Invocation/template arguments.
-- @param {string} frame.args.source Delimited string to split.
-- @param {string} frame.args.dlm Symbol or character to split
-- with.
-- @param[opt] {string} frame.args.pos Initial piece position.
-- Default: `0`.
-- @param[opt] {string} frame.args.lim Maximum number of pieces to
-- append. Default: `1`.
-- @return {string} Percent-encoded string.
-- @usage
--
-- {{string|explode|source string|delimiter|position 0-index|piece limit}}
--
-- @usage
--
-- {{string|explode
-- | source = source string
-- | dlm = delimiter
-- | pos = position 0-index
-- | lim = piece limit
-- }}
--
local str = {}
local ustring, text = mw.ustring, mw.text
function str.explode( frame )
local args = str._getParameters( frame.args, { 'source', 'dlm', 'pos', 'lim' } )
local source = args['source'] or ''
local delim = str._escapePattern( args['dlm'] or ' ' )
local pos = ( tonumber( args['pos'] or '0' ) + 1 )
local pieces = text.split(source, delim)
local limit = tonumber( args['lim'] ) or #pieces
local dividers = {}
for div in ustring.gmatch(source, delim) do
table.insert(dividers, div)
end
if limit < #pieces then
for index, value in ipairs(pieces) do
if index > limit then
pieces[limit] = pieces[limit] .. dividers[index-1] .. value
end
end
for index, value in ipairs(pieces) do
if index > limit then pieces[index] = nil end
end
end
if pos < 1 then
pos = #pieces + pos
end
return pieces[pos] or ''
end
return str