taking off the http or https off a javascript string
我有以下字符串
1 2 3 | http://example.com https://example.com http://www.example.com |
我如何摆脱
试试这个:
1 2 | var url ="https://site.com"; var urlNoProtocol = url.replace(/^https?\:\/\//i,""); |
1 2 3 | var txt="https://site.com"; txt=/^http(s)?:\/\/(.+)$/i.exec(txt); txt=txt[2]; |
对于没有http / https的链接解析,请使用以下命令:
1 2 3 | var txt="https://site.com"; txt=/^(http(s)?:\/\/)?(.+)$/i.exec(txt); txt=txt[3]; |
此答案扩展了上面常见的
感谢上面的答案,这使我想到了这一点!
1 2 3 4 5 6 | 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); |
这是指向代码笔的链接。
1 2 3 | var str ="https://site.com"; str = str.substr( str.indexOf(':') + 3 ); |
除了
1 2 3 | str = str.slice( str.indexOf(':') + 3 ); str = str.substring( str.indexOf(':') + 3 ); |
编辑:似乎问题的要求在另一个答案下的评论中已更改。
如果字符串中可能没有
1 2 3 4 5 | var str ="site.com"; var index = str.indexOf('://'); if( index > -1 ) str = str.substr( index + 3 ); |
另一个有效的解决方案
您可以使用URL()构造函数。它将解析您的url字符串,并且会有一个没有协议的条目。使用正则表达式可以减少头痛:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
尽管
1 | u.host.replace(/^www./, '') // www.facebook.com => facebook.com |
从URL剥离协议:
1 2 | var url ="https://site.com"; var urlNoProto = url.split('/').slice(2).join('/'); |
适用于任何协议,ftp,http,gopher,nntp,telnet,wais,文件,prospero ... RFC 1738中指定的所有协议,但其中没有//的协议除外(mailto,news)。
Javascript使用split函数也可以解决该问题。
太棒了!!!
1 2 3 4 | var url ="https://example.com"; url = url.split("://")[1]; // for https use url..split("://")[0]; console.log(url); |
请注意,在实际网页中,继承协议
因此,我建议regexp也涵盖这种情况:
(您可以对其进行优化)
您可以使用DOM的HTMLHyperlinkElementUtils:
1 2 3 4 5 6 7 8 9 10 11 12 | 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:
假设除了协议外没有其他双斜杠,您可以这样做:
1 2 | var url ="https://example.com"; var noProtocol = url.split('//')[1]; |