Replace subdomain name with other subdomain Using JavaScript?

核能气质少年 提交于 2020-01-24 11:13:05

问题


I'm trying to replace the subdomain name from "news.domain.com/path/.." to "mobile.domain.com/path/..", using JavaScript

Any idea how to achieve this?


回答1:


I'm assuming that you want to change a string in the generic format xxxx.domain.com/... into mobile.domain.com/.... This regexp should do it in JavaScript:

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



回答2:


This should work in normal cases:

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

Use following to add an extra level of validation:

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"));



回答3:


In reference to FixMaker's comment on his answer:

window.location.href will give you a fully qualified URL (e.g. http://news.domain.com/path). You'll need to take into account the http:// prefix when running the above code

A suitable regular expression to handle the request scheme (http/https) is as follows:

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'));



回答4:


If you want to send user to new url via JS - use document.location = "mobile.domain.com/path/..".




回答5:


You cannot replace a subdomain. You can redirect using javascript.

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



回答6:


I tried using java script but no luck and for my case i use the below code in .httaccess file

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

it will replace "news" sub domain to "mobile" sub domain. hope it will help any one.



来源:https://stackoverflow.com/questions/16085276/replace-subdomain-name-with-other-subdomain-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!