gsub javascript 中的一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13999264/
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
gsub a string in javascript
提问by Martin
I try to get only the domain name i.e. google.com
from javascript
我尝试只google.com
从 javascript 中获取域名
document.location.hostname
This code returns www.google.com
.
此代码返回www.google.com
.
How can I only get google.com
? In this case it would be to either remove the www.
or get only the domain name (if there's such a method in javascript).
我怎么只能得到google.com
?在这种情况下,要么删除www.
域名,要么只获取域名(如果 javascript 中有这样的方法)。
回答by Phrogz
var host = location.hostname.replace( /www\./g, '' );
The 'g' flag is for 'global', which is needed if you want a true "gsub" (all matches replaced, not just the first).
'g' 标志用于 'global',如果你想要一个真正的“gsub”(所有匹配被替换,而不仅仅是第一个),这是必需的。
Better, though, would be to get the full TLD:
不过,更好的是获得完整的 TLD:
var tld = location.hostname.replace( /^(.+\.)?(\w+\.\w+)$/, '' );
This will handle domains like foo.bar.jim.jam.com
and give you just jam.com
.
这将处理域之类的,foo.bar.jim.jam.com
并为您提供jam.com
.
回答by Jonathan F
... I'm in chrome right now, and window.location.host
does the trick.
...我现在正在使用 chrome,并且window.location.host
可以解决问题。
EDIT
编辑
So I'm an idiot... BUT hopefully this will redeem:
所以我是个白痴......但希望这会赎回:
An alternate to regex:
正则表达式的替代:
var host = window.location.hostname.split('.')
.filter(
function(el, i, array){
return (i >= array.length - 2)
}
)
.join('.');