简单的正则表达式问题

发布于 2024-11-08 11:34:31 字数 154 浏览 0 评论 0原文

我想从 url 字符串中删除它 http://.....?page=1 我知道这行不通,但我想知道你如何正确地做到这一点。

document.URL.replace("?page=[0-9]", "")

谢谢

I want to remove this from a url string
http://.....?page=1
I know this doesn't work, but I was wondering how you would do this properly.

document.URL.replace("?page=[0-9]", "")

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深爱成瘾 2024-11-15 11:34:31

看来您想摆脱协议和查询字符串。那么,将其余部分连接起来怎么样?

var loc = window.location;

var str = loc.host + loc.pathname + loc.hash;

http://jsfiddle.net/9Ng3Z/


我不完全确定要求是什么,但这相当简单的正则表达式有效。

loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');

这可能是一个幼稚的实现,但请尝试一下,看看它是否适合您的需要。

http://jsfiddle.net/9Ng3Z/1/

It seems like you want to get rid of the protocol and the querystring. So how about just concatenating the remaining parts?

var loc = window.location;

var str = loc.host + loc.pathname + loc.hash;

http://jsfiddle.net/9Ng3Z/


I'm not entirely certain what the requirements are, but this fairly simple regex works.

loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');

It may be a naive implementation, but give it a try and see if it fits your need.

http://jsfiddle.net/9Ng3Z/1/

过期以后 2024-11-15 11:34:31

? 是正则表达式特殊字符。您需要将其转义为文字 ?。还可以使用正则表达式文字

document.URL.replace(/\?page=[0-9]/, "")

? is a regex special character. You need to escape it for a literal ?. Also use regular expression literals.

document.URL.replace(/\?page=[0-9]/, "")
作死小能手 2024-11-15 11:34:31

@patrick dw 的答案是最实用的,但如果您真的对正则表达式解决方案感到好奇,那么我会这样做:

var trimUrl = function(s) {
  var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
  return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"

The answer from @patrick dw is most practical but if you're really curious about a regular expression solution then here is what I would do:

var trimUrl = function(s) {
  var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
  return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"
静谧幽蓝 2024-11-15 11:34:31

你非常接近。要获取 URL,请使用 location.href 并确保转义问号。

var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do

您还可以删除所有查询字符串参数:

var URL = location.href.replace("\?.*", "");

You're super close. To grab the URL use location.href and make sure to escape the question mark.

var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do

You can also strip all query string parameters:

var URL = location.href.replace("\?.*", "");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文