使用JavaScript将子域名替换为其他子域名
Replace subdomain name with other subdomain Using JavaScript?
我正在尝试将子域名从"新闻.domain.com/path/.."替换为"移动.domain.com/path/..",使用JavaScript
知道如何实现这一点吗?
我假设您想将通用格式xxxx.domain.com/...
中的字符串更改为mobile.domain.com/...
。这个正则表达式应该在JavaScript中完成:
var oldPath = "news.domain.com/path/";
var newPath = oldPath.replace(/^[^.]*/, 'mobile')
这应该在正常情况下工作:
"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"));
如果你想通过JS发送用户到新的url -使用document.location = "mobile.domain.com/path/.."
参考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'));
不能替换子域。您可以使用javascript重定向。
<script type="text/javascript">
<!--
window.location = "http://mobile.domain.com/path/to/file.html"
//-->
</script>
我尝试使用java脚本,但没有运气,对于我的情况,我使用下面的代码在。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"子域。希望对大家有所帮助。
相关文章:
- 如何添加浮动和非浮动,其他
- 与其他库的jQuery.noConflict()
- 播放当前视频时如何停止其他视频?JavaScript
- 剑道UI内联编辑:如何在点击其他按钮时隐藏按钮
- 制作一个不带HTML a标记但在动画播放完毕后指向其他页面的超链接
- 除修剪外的其他功能
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- Array.length似乎不起作用;console.log则显示其他情况
- 如何消除代码中的未定义和其他问题
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- Jquery未定义函数正在停止其他操作
- 如何将我的javascript库公开给其他客户端使用
- Javascript阻止其他Javascript代码
- chart.series[id].remove()无法刷新高位图表/高位股票中其他系列的图例属性
- 如何“;过滤器”;或者以其他方式重构该数据
- 使用jquery获取其他域名网站的源代码
- 提取其他域名页面的html
- 使用JavaScript将子域名替换为其他子域名