0

I have a code which does something if port is xxxx. Here is the code:

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

    }

It's working very well. However, I'm stuck with this url which is hardcoded right now.

http://pc-john.example.com:9877/app/private

In this url name can change so I need to do something more felxible, url colud be like this:

 http://pc-jack.example.com:9877/app/private 

or

 http://pc-sara.example.com:9877/app/private 

Can anybody help me with this? Thank you all.

jomskris
  • 293
  • 6
  • 17
  • How do you determine what the URL will be? – Andrew May 02 '19 at 06:21
  • Possible duplicate of [Get protocol, domain, and port from URL](https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url) – Tarmo May 02 '19 at 06:22

2 Answers2

3

You can 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>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

You can possibly use built-in methods that extracts all the parts from href

url.hostname;  //  'google.com'
url.port;      //  8080
url.pathname;  //  '/app/private'
url.protocol;  //  'http:'

or you can explicity use split method and get the port number

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
shikhar
  • 110
  • 10