Module:String2

Uit Wikibooks
Doel
Diverse uitbreidingen op Module:String. Voeg evt. nieuwe functies toe aan deze module.

Functies:

asc() - Geeft de ASCII-waarde van een string. Gebruik en toelichting dmv. Sjabloon:Asc
chr() - Geeft een teken met opgegeven ASCII-waarde. Gebruik en toelichting dmv. Sjabloon:Chr
len() - Geeft de lengte van een string (inclusief evt. spaties aan begin en eind!), dmv. Sjabloon:Len
repeatx() - Herhaalt een teken(-reeks). Gebruik en toelichting dmv. Sjabloon:Repeat
replace_all() - Vervangt (delen van) tekst. Gebruik en toelichting dmv. Sjabloon:Replace
Syntax
{{#Invoke:String2
 |replace_all
 |Te doorzoeken tekst
 |Te vervangen tekst
 |Vervangingstekst
}}
NB.: In geen van de (naamloze) parameters is een isgelijkteken ("=") of accolade ("{" of "}") toegestaan. Gebruik indien nodig de constructie {{Sjabloonnaam | 1= <...> }}.



local p = {}

function p.asc(frame)
 return string.byte(frame.args[1])
end

function p.chr(frame)
 return string.char(frame.args[1])
end

function p.len(frame)
 return string.len(frame.args[1])  -- including leading and trailing spaces!
end

function p.repeatx(frame)
 -- repeatx() because repeat() is not allowed
 return string.rep(frame.args[1], tonumber(frame.args[2]))
end

function p.replace_all(frame)
    -- Returns the first parameter, with all occurences of the second parameter replaced with the third parameter.
    -- All special characters are ignored: {{#invoke:String2|replace_all|test.a%1$foo|%1|bar}} results in `test.abarfoo`.
    local str = frame.args[1]
    local strToFind = frame.args[2]
    local strToreplaceWith = frame.args[3]
    local r = string.gsub(str, p._escape_pattern(strToFind), p._escape_pattern(strToreplaceWith))
    return r
end

function p.trim (frame)
 return (string.gsub(frame.args[1], "^%s*(.-)%s*$", "%1"))
end

-- 

function p._escape_pattern(text)
    -- Takes one string parameter, and returns the string with all characters with special meaning for Lua patterns escaped with a preceding `%`.
    -- Replaces each occurence of any of ().%+-*?[^$ with a `%` and then the character.
    local r = string.gsub(text, "[%(%)%.%%%+%-%*%?%[%^%$]", "%%%1")
    return r
end

p['encode wiki page name'] = function( frame )
	local x = mw.ustring.gsub( 
		frame.args[1] or '', 
		'[\'"&_]', 
		{ 
			["'"] = '&#39;', 
			['"'] = '&#34;', 
			['&'] = '&#38;', 
			['_'] = ' ', 
		} 
	)
	return mw.text.trim( x )
end

return p
Informatie afkomstig van https://nl.wikibooks.org Wikibooks NL.
Wikibooks NL is onderdeel van de wikimediafoundation.