我想用JavaScript将子域名从"news.domain.com/path/.."替换为"mobile.domain.com/path/..",有什么方法实现吗?
我假设您想将一个通用格式的字符串 xxxx.domain.com/...
改为 mobile.domain.com/...
。在 JavaScript 中,可以使用以下正则表达式实现:
var oldPath = "news.domain.com/path/";
var newPath = oldPath.replace(/^[^.]*/, 'mobile')
window.location.href
会给你一个完整的URL(例如 http://news.domain.com/path
)。当运行上述代码时,您需要考虑http://
前缀。 - FixMaker这应该在正常情况下工作:
"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"));
document.location = "mobile.domain.com/path/.."
。适用于处理请求方案(http / https)的正则表达式如下:window.location.href将给你一个完全合格的URL(例如http://news.domain.com/path)。当运行上述代码时,您需要考虑http://前缀
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'));
您无法替换子域名。但可以使用JavaScript进行重定向。
<script type="text/javascript">
<!--
window.location = "http://mobile.domain.com/path/to/file.html"
//-->
</script>
我尝试使用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”子域名。希望能对任何人有所帮助。