Module:String: Difference between revisions

1,428 bytes added ,  11 years ago
add str.replace_plain
m>Dragons flight
(Continuing trials and tribulations of string trimming and Wikipedia template quirks)
m>WOSlinker
(add str.replace_plain)
Line 142: Line 142:
      
      
     return start
     return start
end
--[====[
replace_plain
This function allows one to replace a target string or pattern within another
string.
Usage:
{{#invoke:String|replace_plain|source_str|pattern_string|replace_string|firstonlyflag}}
OR
{{#invoke:String|replace_plain|source=source_str|pattern=pattern_str|replace=replace_string|firstonly=firstonlyflag}}
Parameters
    source: The string to search
    patten: The string or pattern to find within source
    replace: The replacement text
    firstonly: Boolean flag indicating that only the first occurence found should be replaced
]====]
function str.replace_plain( frame )
    local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'firstonly' } );
    local source_str = new_args['source'] or '';
    local pattern = new_args['pattern'] or '';
    local replace = new_args['replace'] or '';
    local firstonly = new_args['firstonly'] or '';
    firstonly = firstonly:lower();
       
    if source_str == '' or pattern == '' then
        return source_str;
    end   
    local pattern_plain = mw.ustring.gsub(pattern, '%%', '%%%%');
    local replace_plain = mw.ustring.gsub(replace, '%%', '%%%%');
    if firstonly == 'true' or firstonly == 'yes' or firstonly == '1' then
        local result = gsub( source_str, pattern_plain, replace_plain, 1 );
    else
        local result = gsub( source_str, pattern_plain, replace_plain, n );
    end
    return result;
end
end


Anonymous user