Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Mathias Valentin 60 posts 208 karma points
    Apr 15, 2016 @ 11:10
    Mathias Valentin
    0

    Replace query string parameter with a regular expression

    Quick question! How do I replace a query string parameter in an url? Lets say I want to replace the width parameter in the string below, with width=360?

    /media/1010/demo.png?width=300&height=200

    In javascript I would do something like:

    url.replace(/width=\d+/, "width=360");
    

    But how to do this in Razor (partial view macro)?

    Happy friday!

  • Tom Steer 161 posts 596 karma points
    Apr 15, 2016 @ 11:50
    Tom Steer
    101

    Hey Mathias,

    Something like this should work:

    Regex.Replace("your url", @"([?&]width)=[^?&]+", "$1=200")
    

    Cheers, Tom

  • Tom Steer 161 posts 596 karma points
    Apr 15, 2016 @ 12:00
    Tom Steer
    1

    Also just as a side note, a great site I find really useful for helping to write regular expressions is: http://regexr.com/ :D

  • Mathias Valentin 60 posts 208 karma points
    Apr 15, 2016 @ 12:07
    Mathias Valentin
    0

    Great! It works - thanks

    Can you tell me how to remove a parameter. Lets say I wanted to remove the height parameter from the string?

    Great sidenote btw!

  • Tom Steer 161 posts 596 karma points
    Apr 15, 2016 @ 12:19
    Tom Steer
    1

    You could use the same regex but change it to replace with an empty string e.g.

    Regex.Replace("your url", @"([?&]height)=[^?&]+", "")
    

    Cheers, Tom

  • Mathias Valentin 60 posts 208 karma points
    Apr 15, 2016 @ 12:21
    Mathias Valentin
    0

    Awesome! Thanks!

  • fatmazayed 41 posts 122 karma points
    Apr 25, 2023 @ 22:54
    fatmazayed
    0

    you can try this

    @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor @{ var url = HttpContextAccessor.HttpContext.Request; string currentURL = string.Concat(url.Host, url.Path,"?item=");

    }

  • @item.Title
    1. get first currentURL without qury string value
    2. then add your current value @string.Concat(url.Scheme, "://",currentURL,item.ItemName)
Copy Link
Please Sign in or register to post replies

Write your reply to:

Draft