The easiest way to manipulate a URL is to first get it into its parsed form. Use URL
for this:
const url = new URL(location.href);
On that URL object are two properties you're interested in. The first is host
, which specifies the hostname and port number. In your example, your first URL would have the host
set to 123.123.123.123:8080
. You could change this to 123.123.123.123:8082
like so:
url.host = '123.123.123.123:8082';
Then to get the string form of the URL:
url.toString(); // http://123.123.123.123:8082/home
The next property you want to manipulate is pathname
, and it works the same way. Just modify that to change the path, and use the url
as a string to get the string version.
Also, unrelated to your question, but please consider using the designated documentation IP addresses in your questions in the future. https://www.rfc-editor.org/rfc/rfc5737 You never know when you might use an example address that might actually be in use by someone.