Mohamed Zouari
Mohamed Zouari

Reputation: 415

How to get the current page URL and use it

I am trying to deploy a project on the Cloud, I need to get the current url of the page, change it and use it. Example: the current url: 123.123.123.123:8080/home and I want to href to 123.123.123.123:8082/add

I want to use a Javascript function to generate "http://localhost:8083/businesss" and use it ..

Upvotes: 2

Views: 364

Answers (3)

Nsoseka
Nsoseka

Reputation: 319

 window.location.href

will return to the you the current url of the page.

Upvotes: 1

Brad
Brad

Reputation: 163593

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.

Upvotes: 0

Rojo
Rojo

Reputation: 2869

Just use window.location.href. Explanation

You can then put window.location.href = "http://localhost:8083/businesss" or whatever href you need.

Upvotes: 0

Related Questions