使用regex从url中删除查询字符串参数

cpe*_*e00 6 javascript regex jquery

我是regex的新手,需要从我们的网址中删除一些内容

 http://mysite.blah/problem/smtp/smtp-open-relay?page=prob_detail&showlogin=1&action=smtp:134.184.90.18
Run Code Online (Sandbox Code Playgroud)

我需要删除"?"中的所有内容 然后,离开我:

http://mysite.blah/problem/smtp/smtp-open-relay
Run Code Online (Sandbox Code Playgroud)

这是我们用于获取路径数据的当前正则表达式.例如,我可以抓住"smtp"和"smtp-open-relay"(我们需要).但是,有时我们的url会根据用户的来源而改变,从而附加查询字符串参数,这会导致我们当前的正则表达式爆炸.

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

我需要它来忽略"?"中的内容.上.

Geo*_*rge 17

正则表达式可能超出您的需要.

您可以执行以下操作以删除其后的?所有内容(查询字符串+哈希):

var routeData = route.split("?")[0];
Run Code Online (Sandbox Code Playgroud)

如果您确实想要仅删除查询字符串,则可以通过从window.location对象重构URL来保留哈希:

var routeData = window.location.origin + window.location.pathname + window.location.hash;
Run Code Online (Sandbox Code Playgroud)

如果您想要查询字符串,可以使用它来阅读window.location.search.


joh*_*ith 5

我只是用过这个

    var routeData= route.substring(0, route.indexOf('?'));
Run Code Online (Sandbox Code Playgroud)


sid*_*mor 5

使用这个函数:

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

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