Replace Subdomain Name With Other Subdomain Using Javascript?
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?
Solution 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')
Solution 2:
This should work in normal cases:
"http://news.domain.com/path/..".replace(/(:\/\/\w+\.)/, "://mobile.")
Use following to add an extra level of validation:
functionreplaceSubdomain(url, toSubdomain) {
const replace = "://" + toSubdomain + ".";
// Prepend http://if (!/^\w*:\/\//.test(url)) {
url = "http://" + url;
}
// Check if we got a subdomain in urlif (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"));
Solution 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:
functionreplaceSubdomain(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'));
Solution 4:
If you want to send user to new url via JS - use document.location = "mobile.domain.com/path/.."
.
Solution 5:
You cannot replace a subdomain. You can redirect using javascript.
<scripttype="text/javascript"><!--
window.location = "http://mobile.domain.com/path/to/file.html"
//--></script>
Post a Comment for "Replace Subdomain Name With Other Subdomain Using Javascript?"