cpeele00
cpeele00

Reputation: 893

Remove querystring parameters from url with regex

I'm pretty new to regex and need to remove some content from our url

 http://mysite.blah/problem/smtp/smtp-open-relay?page=prob_detail&showlogin=1&action=smtp:134.184.90.18

I need to remove everything from the "?" and on, leaving me just:

http://mysite.blah/problem/smtp/smtp-open-relay

Here is our current regex expression we are using to grab the route data. For example I can grab "smtp" and "smtp-open-relay" (which we need). However sometimes our url changes depending on where the user is coming from thereby appending the querystring parameters which is causing our current regex expression to blow up.

// Retrieve the route data from the route
var routeData = /([0-9a-zA-Z_.-]+)\/([0-9a-zA-Z_.-]+)$/g.exec(route);

I need it to ignore stuff from the "?" on.

Upvotes: 9

Views: 31649

Answers (5)

Pratap Singh
Pratap Singh

Reputation: 429

Following is the cleaner way to remove a given parameter say: prop1 form querystring of url. Querystring can be found in url by accessing

window.location.search

Here you apply regular expression for prop1:

var queryStringWithoutProp1=window.location.search.replace(/(&?prop1=)(.[^&]*)/,"");

queryStringWithoutProp1 must return querystring without prop1=value parameter-value combination from querystring

Note: '&?' ensures whether prop1 appears as first parameter or any subsequent one.

Upvotes: 0

sidanmor
sidanmor

Reputation: 5189

Use this function:

var getCleanUrl = function(url) {
  return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};

// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));

Upvotes: 5

john Smith
john Smith

Reputation: 17926

i just used this one

    var routeData= route.substring(0, route.indexOf('?'));

Upvotes: 5

George
George

Reputation: 4257

A regular expression is probably more than you need.

You could do the following to remove the ? and everything (query string + hash) after it:

var routeData = route.split("?")[0];

If you truly wanted to strip only the query string, you could preserve the hash by reconstructing the URL from the window.location object:

var routeData = window.location.origin + window.location.pathname + window.location.hash;

If you want the query string, you can read it with window.location.search.

Upvotes: 23

Trevor Dixon
Trevor Dixon

Reputation: 24382

If you're doing this in-browser, let the browser do the parsing:

location.origin + location.pathname

Or for arbitrary URLs:

function withoutQS(_url) {
    var url = document.createElement('a');
    url.href = _url;
    return url.origin + url.pathname;
}

Upvotes: 0

Related Questions