7

我对正则表达式很陌生,需要从我们的网址中删除一些内容

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

我需要从“?”中删除所有内容。等等,只剩下我:

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

这是我们当前用于获取路线数据的正则表达式。例如,我可以抓取“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);

我需要它来忽略“?”中的内容。上。

4

5 回答 5

20

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

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

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

如果您真的只想去除查询字符串,您可以通过从window.location对象重构 URL 来保留哈希:

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

如果你想要查询字符串,你可以用window.location.search.

于 2013-08-21T19:40:12.060 回答
5

我刚用了这个

    var routeData= route.substring(0, route.indexOf('?'));
于 2013-08-21T19:41:28.860 回答
3

使用这个功能:

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

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

于 2017-08-17T12:19:31.357 回答
0

如果您在浏览器中执行此操作,请让浏览器进行解析:

location.origin + location.pathname

或者对于任意 URL:

function withoutQS(_url) {
    var url = document.createElement('a');
    url.href = _url;
    return url.origin + url.pathname;
}
于 2013-08-21T19:39:39.343 回答
0

以下是删除给定参数的更简洁方法say:prop1 form querystring of url。可以通过访问在 url 中找到查询字符串

窗口位置搜索

在这里,您为 prop1 应用正则表达式:

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

queryStringWithoutProp1 必须从 querystring 返回不带 prop1=value 参数-值组合的查询字符串

注意: '&?' 确保 prop1 是作为第一个参数出现还是作为任何后续参数出现。

于 2019-03-22T07:40:19.810 回答