我有一个代码,如果端口为xxxx,可以做某事。这是代码:
function port() {
if (window.location.port === "9876") {
window.location = "http://pc-john.example.com:9877/app/private";
}
else {
window.location = "http://pc-john.example.com:9876/app/private";
}
}
它运行良好。但是,我遇到了这个网址,该URL现在是硬编码的。
http://pc-john.example.com:9877/app/private
在此URL名称中可以更改,因此我需要做一些更可亲的事情,url colud是这样的:
http://pc-jack.example.com:9877/app/private
或
http://pc-sara.example.com:9877/app/private
有人可以帮助我吗?谢谢大家。
您可以 set location.port
。
if(location.port === "9876") {
location.port = "9877";
}
anchor.port = "9877";
console.log(anchor.href);
<a href="http://pc-john.example.com:9876/app/private" id="anchor">test</a>
您可以使用内置方法,从HREF
提取所有部分url.hostname; // 'google.com'
url.port; // 8080
url.pathname; // '/app/private'
url.protocol; // 'http:'
,或者您可以使用拆分方法并获取端口号
let stringURL = "http://pc-john.example.com:9877/app/private"
let splittedUrl = stringURL.split(':'); //['http://pc-john.example.com','9877/app/private']
let seondSplit = splittedUrl[1].split('/') //['9877','app','private']
let portnumber = secondSplit[0] // 9877