从JavaScript字符串中删除http或https

29

我有以下字符串

http://example.com
https://example.com
http://www.example.com

如何去掉 http:// 或者 https://


3
可能有点跑题,但如果你的目的是链接到当前位置相同的方案,你可以使用 //site.com - Nick Craver
13个回答

57

尝试使用以下代码:

var url = "https://site.com";
var urlNoProtocol = url.replace(/^https?\:\/\//i, "");

9
它可以同时使用http和https。 "s"字符是可选的。 - ncardeli
我真的很喜欢这段代码的简洁。我不明白你第二个正则表达式的必要性...第一个正则表达式会删除http/https协议(如果存在)。如果不存在,就没有什么需要替换的了,字符串会原样返回。 - some
你说得对,我不知道当时在想什么。我会编辑我的回答。 - ncardeli
6
冒号前面的转义符是不必要的。url.replace(/^https?:\/\//i, "") 与之等效。 - IanVS
1
我建议使用 .replace(/^\/\/|^.*?:(\/\/)?/, ''); 来获得更好的跨协议支持。 - gdibble

40
您可以像这样使用URL对象const urlWithoutProtocol = new URL(url).host;

5
我建议人们大力点赞这个答案,新的URL对象功能现在是处理许多URL情况的最佳方法。 - Anthony
这将仅在 //site.com 上失败。 - Toniq

7

您可以使用URL()构造函数。它将解析您的url字符串,并且会有一个不带协议的条目。因此,使用正则表达式时会更加轻松:

let u = new URL('https://www.facebook.com/companypage/');
URL {
    hash: ""
    host: "www.facebook.com"
    hostname: "www.facebook.com"
    href: "https://www.facebook.com/companypage/"
    origin: "https://www.facebook.com"
    password: ""
    pathname: "/companypage/"
    port: ""
    protocol: "https:"
    search: ""
    searchParams: URLSearchParams {}
    username: ""
}
u.host // www.facebook.com
u.hostname // www.facebook.com

虽然URL()方法会去掉协议,但它仍会保留www部分。在我的情况下,我也想要去掉子域名部分,因此不得不使用.replace()方法。

u.host.replace(/^www./, '') // www.facebook.com => facebook.com

4
var txt="https://site.com";
txt=/^http(s)?:\/\/(.+)$/i.exec(txt);
txt=txt[2];

如果需要解析没有http/https的链接,请使用以下方法:

var txt="https://site.com";
txt=/^(http(s)?:\/\/)?(.+)$/i.exec(txt);
txt=txt[3];

工作得很好,但如果字符串可能有或可能没有http://,有些已经以site.com的格式出现了,那么它就会失败。 - Matt Elhotiby
txt=/(?:https?:\/\/)?(.*)$/i.exec(txt)[1];不需要捕获http或https,使用*而不是+,以便仅包含 https?:// 的字符串将返回一个空字符串。 - some

2

这个答案扩展了一些上面的答案,包括http://https://或者//,这也是常见的。

感谢上面的答案让我找到了这个!

const urls = [ "http://example.com", "https://example.com", "//example.com" ]

// the regex below states: replace `//` or replace `//` and the 'stuff'
const resolveHostNames = urls.map(url => url.replace(/\/\/|.+\/\//, ''))

console.log(resolveHostNames);

这里有一个 CodePen 的链接

这实际上是最佳解决方案。 - stackoverflow

2
var str = "https://site.com";

str = str.substr( str.indexOf(':') + 3 );

在这种情况下,你可以使用.slice().substring()代替.substr()。它们都会产生相同的结果。

str = str.slice( str.indexOf(':') + 3 );

str = str.substring( str.indexOf(':') + 3 );

如果字符串中可能没有"http://",则执行以下操作:
var str = "site.com";

var index = str.indexOf('://');
if( index > -1 )
   str = str.substr( index + 3 );

2
我喜欢这个,非常简单,不需要正则表达式。@Jacob 看起来对我来说是完全有效的 JavaScript? - Mads Mogenshøj
将 "site.com" 转换为 "te.com",但是... idx = str.indexOf(':') if(idx >= 0){ str = str.substr(idx + 3); } - Mike Ruhlin
如果您想解析两种情况(有http/没有http),您必须使用正则表达式,或者重复正则表达式引擎的工作,并使用字符串函数自己制作。哪个更好? - Bick

1

从URL中去除协议:

var url = "https://site.com";
var urlNoProto = url.split('/').slice(2).join('/');

适用于任何协议,包括ftp、http、gopher、nntp、telnet、wais、file、prospero……所有在RFC 1738中指定的协议,除了没有“//”的协议(如mailto、news)。


1
另一个高效的解决方案是:url.replace(/(^(\w+:)?\/\//, '')

1

0
你可以使用 DOM 中的 HTMLHyperlinkElementUtils
function removeProtocol(url) {
  const a = document.createElement('a');
  a.href = url;
  // `url` may be relative, but `a.href` will be absolute.
  return a.href.replace(a.protocol + '//', '');
}

removeProtocol('https://example.com/https://foo');
// 'example.com/https://foo'

removeProtocol('wrong://bad_example/u');
// 'bad_example/u'

来自MDN上的HTMLHyperlinkElementUtils

a.hostnameexample.com
a.hostexample.com:3000
a.pathname/foo/bar.html
a.search?a=1&b=2
a.hash#goo
a.usernamea.passworda.port等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接