Module:String

From Wikibooks, open books for an open world
Jump to: navigation, search
Documentation[edit] [history] [purge]

Examples

  • {{#invoke:string|sub|[[Help:Contents]]|3|-3}} → Help:Contents
  • {{#invoke:string|length|Help:Contents}} → 13
  • {{#invoke:string|find|Help:Contents|Contents}} → 6
  • {{#invoke:string|find|Help:Contents|Contents|yes|no}} → yes
  • {{#invoke:string|find|Help:Contents|ABC|yes|no}} → no
  • {{#invoke:string|replace|Help:Contents|Contents|Lua}} → Help:Lua
  • {{#invoke:string|trim|--Help:Contents--|-}} → Help:Contents
return {
    sub = (function (frame)
        local args, pargs = frame.args, frame:getParent().args
        return mw.ustring.sub( args[1] or pargs[1] or "", tonumber( args[2] or pargs[2] ), tonumber( args[3] or pargs[3] ) )
    end),
    length = (function (frame)
        local args, pargs = frame.args, frame:getParent().args
        return mw.ustring.len( args[1] or pargs[1] or "" )
    end),
    find = (function (frame)
        local args, pargs = frame.args, frame:getParent().args
        local start = tonumber( args[3] or pargs[3] )
        local res = mw.ustring.find( args[1] or pargs[1] or "", args[2] or pargs[2] or "", start or 1, true  )
 
        start = res and (start and 4 or 3) or (start and 5 or 4)
        res = res or ""
        return args[start] or pargs[start] or res
    end),
    replace = (function (frame)
        local args, pargs = frame.args, frame:getParent().args
        local res = mw.ustring.gsub(
            args[1] or pargs[1] or "",
            mw.ustring.gsub( args[2] or pargs[2] or "", "([][^$%%.*+-?])", "%%%1" ),
            args[3] or pargs[3] or "",
            tonumber( args[4] or pargs[4] )
        )
        return res
    end),
    trim = (function (frame)
        local args, pargs = frame.args, frame:getParent().args
        local what = mw.ustring.gsub( args[2] or pargs[2] or "", "([][^$%%.*+-?()])", "%%%1" )
        local res = mw.ustring.gsub(
            mw.ustring.gsub( args[1] or pargs[1] or "", "^[" .. what .. "]*", "" ),
            "[" .. what .. "]*$",
            ""
        )
        return res
    end),
}