使用JavaScript替换子域名名称为其他子域名?

6
我想用JavaScript将子域名从"news.domain.com/path/.."替换为"mobile.domain.com/path/..",有什么方法实现吗?

1
正如其他人所暗示的,您能否更清楚地说明您想要实现什么:您是想将用户的浏览器重定向到新的URL,还是只想知道如何将第一个字符串转换为第二个字符串? - FixMaker
我想将URL中子域名名称news替换为mobile,以便显示页面的移动版本。 - Bala
6个回答

6

我假设您想将一个通用格式的字符串 xxxx.domain.com/... 改为 mobile.domain.com/...。在 JavaScript 中,可以使用以下正则表达式实现:

var oldPath = "news.domain.com/path/";
var newPath = oldPath.replace(/^[^.]*/, 'mobile')

我该如何获取当前路径(旧路径),因为URL是动态的? - Bala
我尝试了以下代码:var oldPath = window.location.href; var newPath = oldPath.replace(/^[^.]*/, 'mobile'); document.location = newPath;但是没有成功。 - Bala
1
@Bala,window.location.href会给你一个完整的URL(例如 http://news.domain.com/path)。当运行上述代码时,您需要考虑http://前缀。 - FixMaker

5

这应该在正常情况下工作:

"http://news.domain.com/path/..".replace(/(:\/\/\w+\.)/, "://mobile.")

使用以下内容添加额外的验证级别:

function replaceSubdomain(url, toSubdomain) {
    const replace = "://" + toSubdomain + ".";

    // Prepend http://
    if (!/^\w*:\/\//.test(url)) {
        url = "http://" + url;
    }

    // Check if we got a subdomain in url
    if (url.match(/\.\w*\b/g).length > 1) {
        return url.replace(/(:\/\/\w+\.)/, replace)
    }

    return url.replace(/:\/\/(\w*\.)/, `${replace}$1`)
}

console.log(replaceSubdomain("example.com", "mobile"));
console.log(replaceSubdomain("http://example.com:4000", "mobile"));
console.log(replaceSubdomain("www.example.com:4000", "mobile"));
console.log(replaceSubdomain("https://www.example.com", "mobile"));
console.log(replaceSubdomain("sub.example.com", "mobile"));


-1
如果您想通过JS将用户发送到新的URL,请使用document.location = "mobile.domain.com/path/.."

-1
关于FixMaker在他答案中的评论:

window.location.href将给你一个完全合格的URL(例如http://news.domain.com/path)。当运行上述代码时,您需要考虑http://前缀

适用于处理请求方案(http / https)的正则表达式如下:

function replaceSubdomain(url, subdomain){
    return url.replace(/^(https?:\/\/)(www\.)?([^.])*/, `$1$2${subdomain}`);
}

let url1 = 'https://sub-bar.main.com';
let url2 = 'https://www.sub-bar.main.com';

console.log(replaceSubdomain(url1, 'foobar'));
console.log(replaceSubdomain(url2, 'foobar'));


-3

您无法替换子域名。但可以使用JavaScript进行重定向。

<script type="text/javascript">
<!--
window.location = "http://mobile.domain.com/path/to/file.html"
//-->
</script>

1
我知道如何重定向域名,我想在URL中将单词“news”更改为“mobile”。 - Bala

-3

我尝试使用JavaScript,但没有成功,对于我的情况,我在.httaccess文件中使用以下代码

RewriteCond %{HTTP_USER_AGENT} "iphone|ipod|android" [NC]
RewriteCond %{HTTP_HOST} !^mobile.domain.com
RewriteRule ^(.*)$ http://mobile.domain.com/ [L,R=302]

它将把“news”子域名替换为“mobile”子域名。希望能对任何人有所帮助。


当问题明确要求JavaScript解决方案时,这怎么可能是正确的呢? - moefinley
@moefinley 至少那时我已经掌握了这种方法,所以它对我帮助很大。 - Bala

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