没有 www 的 Javascript location.host

标签 javascript

我有一个 php 文件,用于在 Facebook 和 Twitter 上分享我的用户的帖子。例如,如果我点击 Twitter 图标,我会看到一个屏幕,其中自动写入了指向我网站的超链接。这很好,但我想删除自动显示在 Twitter 屏幕上的 url 的 www. 部分。我猜这与 location.host 有关,所以我用 google 搜索,但找不到这个问题的正确答案。

这是我的代码示例:

function e(f,i,an)
{
        with(document)
        {
                write('<div style="width:100%"><table id=m'+i+' style="visibility:hidden"><tr>');
                write('<td id="vst' + i + '" style="white-space:nowrap">&nbsp;</td>');
                write('<td hr(this.childNodes[0])" title="share on facebook"><a href="javascript:od(\'http://www.facebook.com/sharer.php?u=' + location.host + '/e/'+ i +'\',900,400)" class=icon><img src="images/facebook.png" target="_blank"></a></td>');
        write('<td hr(this.childNodes[0])" title="share on twitter"><a href="javascript:od(\'http://twitter.com/home?status=' + location.host + '/e/'+ i +' - %20read!\',800,600)" class=icon><img src="images/twitter.png" target="_blank"></a></td>');
                write('<td class=ei><a name="cid'+i+'"></a><a href="e/'+i+'">( #'+i+' )</a></td>'); 

                  document.write('<td>&nbsp;</td>');

我的第二个问题是:如何在 Twitter 屏幕上添加自定义标题:例如,我的网站名称无需使用 location.host 以及正在共享的 TOPICNAME 的标题?

最佳答案

对于您的第一个……您可以修改主机:

location.host.replace('www.','')

编辑:解决问题

再次被否决,并看到第一条评论有很多赞成票,我将尝试解决对 www 之外包含 www 的子域的担忧。 ..

这个解决方案仍然避开正则表达式,主要是因为通常更难维护正则表达式,而且有很多开发人员根本不接触正则表达式...

var cleaned_host;
if(location.host.indexOf('www.') === 0){
    cleaned_host = location.host.replace('www.','');
}
// do something with `cleaned_host`

...或更简洁...

location.host.indexOf('www.') && location.host || location.host.replace('www.', '');
// evaluates to hostname with starting `www.` removed

关于没有 www 的 Javascript location.host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12543746/

相关文章:

javascript - 为什么一直设置新的间隔时间间隔会越来越快

javascript - 如何通过 API 启动 hyper.sh 容器? (接收“执行失败 : no such file or directory error)

javascript - Aurelia 中的嵌套重复无法识别对象数组

javascript - 连接多个对象的第一个字段

javascript - 使用模式弹出查看器显示目录中的 PHP 图像

javascript - 使用 styled-component 在父组件的悬停状态下隐藏子组件

javascript - 如何从 javascript/google 应用程序脚本中的外部函数和同级函数调用函数

javascript - 我的 anchor 属性的动态 onclick 未触发

javascript - 如何在 jquery 方法中创建 if 语句

javascript - 在 Node.js 中的异步函数中填充数组