Need to remove specific parameter from url

I am new to the Lua library, I have one use case which I have to remove on a specific parameter and its value: for example:

String 1 : ?xyz=true&toekn=4234dadsasda

String 2 : ?toekn=4234dadsasda&test=pass

Need output like this after removing token and its value

String 1 : ?xyz=true

String 2 : ?test=pass

I have tried the below Lua gsub function but no luck:

string.gsub(args, "token=.*", " ")

any help apricated, thanks

2 answers

  • answered 2021-02-22 22:43 Wiktor Stribiżew

    If you can only have two query params and no more than two as shown in your input you can use

    text:gsub("&?token=[^&]+&?", "")

    Or, if you have multiple query params, you can use

    text:gsub("([&?])token=[^&]+&?", "%1"):gsub("(.*)&$", "%1")

    See the online Lua demo #1 and the online Lua demo #2.


    • &? - an optional &
    • token= - a literal string
    • [^&]+ - one or more chars other than &
    • &? - an optional & char.

    In the second solution, :gsub("([&?])token=[^&]+&?", "%1") replaces the match with either ? or & before the token, and the next gsub("(.*)&$", "%1") removes the & at the end of string in case the param occurs at the end of string.

  • answered 2021-02-23 06:11 Paul Kulchenko

    You may want to considers additional conditions (using & and ; as separators[1]) and corner cases (trailing separators and substrings with token):

      function(s1, s2) return s1 and s2 and #(s1..s2) > 1 and s1 or "" end)

    This solution works correctly on query strings that include parameters like subtoken and that use ; as separators. The template is using %f[%a], which is a frontier pattern that describes a zero-length boundary where non-letter changes to a letter (this includes the first character in a string).

    [1] W3C recommends that all web servers support semicolon separators in addition to ampersand separators to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands (wikipedia article on query string).