Module:String: Difference between revisions
Appearance
No edit summary |
|||
Line 59: | Line 59: | ||
Parameters | Parameters | ||
s: The string to return a subset of | s: The string to return a subset of | ||
i: The | i: The first index of the substring to return, defaults to 1. | ||
j: The last index of the string to return, defaults to the last character. | j: The last index of the string to return, defaults to the last character. | ||
Line 94: | Line 94: | ||
return mw.ustring.sub( s, i, j ) | return mw.ustring.sub( s, i, j ) | ||
end | |||
--[[ | |||
This function implements that features of {{str sub old}} and is kept in order | |||
to maintain these older templates. | |||
]] | |||
function str.sublength( frame ) | |||
local i = tonumber( frame.args.i ) or 0 | |||
local len = tonumber( frame.args.len ) | |||
return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) ) | |||
end | end | ||
Line 279: | Line 289: | ||
return mw.ustring.sub( target_str, pos, pos ) | return mw.ustring.sub( target_str, pos, pos ) | ||
end | |||
--[[ | |||
str_find | |||
This function duplicates the behavior of {{str_find}}, including all of its quirks. | |||
This is provided in order to support existing templates, but is NOT RECOMMENDED for | |||
new code and templates. New code is recommended to use the "find" function instead. | |||
Returns the first index in "source" that is a match to "target". Indexing is 1-based, | |||
and the function returns -1 if the "target" string is not present in "source". | |||
Important Note: If the "target" string is empty / missing, this function returns a | |||
value of "1", which is generally unexpected behavior, and must be accounted for | |||
separatetly. | |||
]] | |||
function str.str_find( frame ) | |||
local new_args = str._getParameters( frame.args, {'source', 'target'} ) | |||
local source_str = new_args['source'] or '' | |||
local target_str = new_args['target'] or '' | |||
if target_str == '' then | |||
return 1 | |||
end | |||
local start = mw.ustring.find( source_str, target_str, 1, true ) | |||
if start == nil then | |||
start = -1 | |||
end | |||
return start | |||
end | end | ||
Line 366: | Line 407: | ||
if plain then | if plain then | ||
pattern = str._escapePattern( pattern ) | pattern = str._escapePattern( pattern ) | ||
replace = | replace = string.gsub( replace, "%%", "%%%%" ) --Only need to escape replacement sequences. | ||
end | end | ||
Line 469: | Line 510: | ||
end | end | ||
return table.concat( args, sep or '' ) | return table.concat( args, sep or '' ) | ||
end | end | ||
Line 560: | Line 583: | ||
]] | ]] | ||
function str._escapePattern( pattern_str ) | function str._escapePattern( pattern_str ) | ||
return | return ( string.gsub( pattern_str, "[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%0" ) ) | ||
end | end | ||
return str | return str |