given is an URL like http://localhost:1973/Services.aspx?idProject=10&idService=14
.
What is the most straightforward way to replace both url-parameter values(for example 10 to 12 and 14 to 7)?
Regex, String.Replace, Substring or LinQ - i'm a little stuck.
Thank you in advance,
Tim
I ended with following, that's working for me because this page has only these two parameter:
string newUrl = url.Replace(url.Substring(url.IndexOf("Services.aspx?") + "Services.aspx?".Length), string.Format("idProject={0}&idService={1}", Services.IdProject, Services.IdService));
But thank you for your suggestions :)
If you have several parameters with the same name, you can append to the regex global flag, like this text. replace(/(src=). *?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.
URL parameters can potentially cause a lot of problems when it comes to your SEO. For example, they can create duplicate content, waste crawl budget, and dilute ranking signals.
Here is my implementation:
using System;
using System.Collections.Specialized;
using System.Web; // For this you need to reference System.Web assembly from the GAC
public static class UriExtensions
{
public static Uri SetQueryVal(this Uri uri, string name, object value)
{
NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);
nvc[name] = (value ?? "").ToString();
return new UriBuilder(uri) {Query = nvc.ToString()}.Uri;
}
}
and here are some examples:
new Uri("http://host.com/path").SetQueryVal("par", "val")
// http://host.com/path?par=val
new Uri("http://host.com/path?other=val").SetQueryVal("par", "val")
// http://host.com/path?other=val&par=val
new Uri("http://host.com/path?PAR=old").SetQueryVal("par", "new")
// http://host.com/path?PAR=new
new Uri("http://host.com/path").SetQueryVal("par", "/")
// http://host.com/path?par=%2f
new Uri("http://host.com/path")
.SetQueryVal("p1", "v1")
.SetQueryVal("p2", "v2")
// http://host.com/path?p1=v1&p2=v2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With