如何从 JavaScript 中的 URL 中删除“http://”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8206269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove 'http://' from a URL in JavaScript
提问by Peter
I have run into an odd situation. I'm writing a JavaScript bookmarklet that will allow users to click and share external websites to our website very easily and quickly. It simply get's the title, page URL, and if they've selected any text on the page, it grabs it too.
我遇到了一个奇怪的情况。我正在编写一个 JavaScript 书签,它允许用户非常轻松快速地单击外部网站并将其共享到我们的网站。它只是获取标题、页面 URL,如果他们选择了页面上的任何文本,它也会抓取它。
The problem is it doesn't work with external domains for some reason, so if we use it internally we end up with a share window with the URL formatted like this:
问题是由于某种原因它不适用于外部域,所以如果我们在内部使用它,我们最终会得到一个共享窗口,其 URL 格式如下:
http://internaldomain.com/sharetool.php?shareid=http://internaldomain.com/anotheroddpage.html&title=....
http://internaldomain.com/sharetool.php?shareid=http://internaldomain.com/anotheroddpage.html&title=....
That works just fine, BUT if we try to use an external domain and end up with a URL formatted like this:
这工作得很好,但是如果我们尝试使用外部域并最终得到一个格式如下的 URL:
Then we get a Forbidden Erroron our page and can't load it... If we manually remove the http://
from the externaldomain address, it loads just fine again.
然后我们在我们的页面上收到一个禁止错误并且无法加载它......如果我们http://
从外部域地址手动删除它,它再次加载就好了。
So.. I'm thinking the best solution to get around this problem is to modify the JavaScript bookmarklet to remove the http
as it's loading the window. Here is how my current bookmarklet looks:
所以.. 我认为解决这个问题的最佳解决方案是修改 JavaScript 书签以在http
加载窗口时删除它。这是我当前书签的外观:
javascript:var d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://internaldomain.com/sharetool.php',l=d.location,e=encodeURIComponent,u=f+'?u='+e(l.href)+
As you can see, e(l.href)
is where the URL is passed.
如您所见,e(l.href)
是传递 URL 的地方。
How can I modify that so it removes the external domains http://
?
如何修改它以删除外部域http://
?
回答by FailedDev
I think it would be better to take into account all possible protocols.
我认为最好考虑所有可能的协议。
result = url.replace(/(^\w+:|^)\/\//, '');
回答by matsko
url = url.replace(/^https?:\/\//,'')
回答by shyam
l.href.replace(/^http:\/\//, '')
回答by idanzalz
I think the regular expression you need is /(?:http://)(.*)/i
. The first match of this should be it.
我认为您需要的正则表达式是/(?:http://)(.*)/i
. 第一场比赛应该是这样。