I have URL string like:
"http://www.xyz/path1/path2/path3?param1=value1¶m2=value2".
I need to get this url without parameters, so the result should be:
"http://www.xyz/path1/path2/path3".
I have done it this way:
private String getUrlWithoutParameters(String url) { return url.substring(0,url.lastIndexOf('?')); }
Are there any better ways to do it?
Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you. To use it, simply do something like this: var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL);
To remove a querystring from a url, use the split() method to split the string on a question mark and access the array element at index 0 , e.g. url. split('? ')[0] . The split method will return an array containing 2 substrings, where the first element is the url before the querystring.
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.
URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).
I normally use
url.split("\\?")[0]
Probably not the most efficient way, but more type safe :
private String getUrlWithoutParameters(String url) throws URISyntaxException { URI uri = new URI(url); return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, // Ignore the query part of the input url uri.getFragment()).toString(); }
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