• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Redirecting to a relative URL in JavaScript

My problem is that I want to redirect via JavaScript to a directory above.

The URL looks like this:

example.com/path/folder/index.php?file=abc&test=123&lol=cool

The redirect affect just this:

example.com/path/&test=123&lol=cool

But want to have this:

example.com/path/

How can I do it?

Gass's user avatar

8 Answers 8

You can do a relative redirect:

Kobi's user avatar

If you use location.hostname you will get your domain.com part. Then location.pathname will give you /path/folder. I would split location.pathname by / and reassemble the URL. But unless you need the querystring, you can just redirect to .. to go a directory above.

ygrichman's user avatar

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

Shaun Luttin's user avatar

redirect to ../

Chris Ballance's user avatar

<a href="..">no JS needed</a>

.. means parent directory.

Kornel's user avatar

I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:

Timo Tijhof's user avatar

try following js code

location = '..'

Kamil Kiełczewski's user avatar

This is an old question but just to provide more information, this is how urls work:

Teocci's user avatar

Not the answer you're looking for? Browse other questions tagged javascript url redirect or ask your own question .

Hot Network Questions

window location change path

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Related Articles

How to redirect to a relative URL in JavaScript?

This works in the same way as redirecting to any URL in javascript.

window.location.href returns the href (URL) of the current page

Example 1: A simple redirecting program

Both windows.location.href and document.location.href are same.

Example 2: A simple redirecting program

Please Login to comment...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

# window.location Cheatsheet

Looking for a site's URL information, then the window.location object is for you! Use its properties to get information on the current page address or use its methods to do some page redirect or refresh 💫

https://www.samanthaming.com/tidbits/?filter=JS#2

# window.location Properties

# difference between host vs hostname.

In my above example, you will notice that host and hostname returns the value. So why do these properties. Well, it has do with the port number. Let's take a look.

URL without Port

https://www.samanthaming.com

URL with Port

https://www.samanthaming.com:8080

So host will include the port number, whereas hostname will only return the host name.

# How to change URL properties

Not only can you call these location properties to retrieve the URL information. You can use it to set new properties and change the URL. Let's see what I mean.

Here's the complete list of properties that you can change:

The only property you can't set is window.location.origin . This property is read-only.

# Location Object

The window.location returns a Location object. Which gives you information about the current location of the page. But you can also access the Location object in several ways.

The reason we can do this is because these are global variables in our browser.

window location change path

# window.location vs location

All 4 of these properties point at the same Location object. I personally prefer window.location and would actually avoid using location . Mainly because location reads more like a generic term and someone might accidentally name their variable that, which would override the global variable. Take for example:

I think that most developer is aware that window is a global variable. So you're less likely to cause confusion. To be honest, I had no idea location was a global variable until I wrote this post 😅. So my recommendation is to be more explicit and use window.location instead 👍

Here's my personal order of preference:

Of course, this is just my preference. You're the expert of your codebase, there is no best way, the best way is always the one that works best for you and your team 🤓

# window.location Methods

# window.location.tostring.

This method returns the USVString of the URL. It is a read-only version of Location.href

In other words, you can use it to get the href value from the

on this 😊. But I did find a performance test on the difference.

JSPerf: Location toString vs Location href

One thing I want to note about these speed tests is that it is browser specific. Different browser and versions will render different outcome. I'm using Chrome, so the href came out faster then the rest. So that's one I'll use. Also I think it reads more explicit then toString() . It is very obvious that href will provide the URL whereas toString seems like something it being converted to a string 😅

# assign vs replace

Both of these methods will help you redirect or navigate to another URL. The difference is assign will save your current page in history, so your user can use the "back" button to navigate to it. Whereas with replace method, it doesn't save it. Confused? No problem, I was too. Let's walk through an example.

Current Page

I just need to emphasize the "current page" in the definition. It is the page right before you call assign or replace .

# How to Do a Page Redirect

By now, you know we can change the properties of the window.location by assigning a value using = . Similarly, there are methods we can access to do some actions. So in regards to "how to redirect to another page", well there are 3 ways.

# replace vs assign vs href

All three does redirect, the difference has to do with browser history. href and assign are the same here. It will save your current page in history, whereas replace won't. So if you prefer creating an experience where the navigation can't press back to the originating page, then use replace 👍

So the question now is href vs assign . I guess this will come to personal preference. I like the assign better because it's a method so it feels like I'm performing some action. Also there's an added bonus of it being easier to test. I've been writing a lot of Jest tests, so by using a method, it makes it way easier to mock.

But for that that are rooting for href to do a page redirect. I found a performance test and running in my version of Chrome, it was faster. Again performance test ranges with browser and different versions, it may be faster now, but perhaps in future browsers, the places might be swapped.

JSPerf: href vs assign

# Scratch your own itch 👍

Okay, a bit of a tangent and give you a glimpse of how this cheatsheet came to be. I was googling how to redirect to another page and encountered the window.location object. Sometimes I feel a developer is a journalist or detective - there's a lot of digging and combing through multiple sources for you to gather all the information available. Honestly, I was overwhelmed with the materials out there, they all covered different pieces, but I just wanted a single source. I couldn't find much, so I thought, I'll cover this in a tidbit cheatsheet! Scratch your own itch I always say 👍

# Community Input

: This is awesome, I’ve used window.location.href in the past, but didn’t realise how simple it is to access sections of the URL!

If you want to see a live-action of what James is talking about, check out the table of content at the top of this article. Click on it and it will scroll down to the specific section of the page.

# Resources

Related Tidbits

Console.table to display data, colorful console message, window.location cheatsheet, fresh tidbits.

Code snippet on HTML abbr Tag

HTML abbr Tag

Code snippet on How to Pad a String with padStart and padEnd in JavaScript

How to Pad a String with padStart and padEnd in JavaScript

Code snippet on Avoid Empty Class in Vue with Null

Avoid Empty Class in Vue with Null

Code snippet on Fix Text Overlap with CSS white-space

Fix Text Overlap with CSS white-space

Code snippet on How to Check if Object is Empty in JavaScript

How to Check if Object is Empty in JavaScript

How TO - Redirect to Another Webpage

Learn how to redirect to another webpage using JavaScript.

Redirect a Webpage

There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace :

Note: The difference between href and replace, is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.

Tip: For more information about the Location Object, read our Location Object Reference .

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

window location change path

Get certified by completing a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

All About Code

May 13, 2019

Member-only

How do you redirect to another page in Javascript?

There are many ways to redirect to another page. But which is the best?

More from All About Code

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

All About Code

Text to speech

window location change path

How to Redirect to a Relative URL in JavaScript?

Redirecting to a normal URL means sending the user to a URL no matter what that URL is or where it is placed. Directing to a relative URL means redirecting the user to a webpage placed in the same directory as the parent page or home page. Relative URLs can also be used to redirect to files placed in other directories, but the Relative URL would contain only the path and no other information like the domain.

This article will explain two different methods to redirect users to relative URLs but before that, quickly set up two different web pages by using the steps below:

Setting up the two HTML Documents

Create a new HTML document named home and put the following lines inside it:

This will display the following webpage on the browser:

window location change path

After that, create another HTML document in the same directory (this is important to make it a relative URL) and name it as secondPage.html . After that, type the following lines in the secondPage.html:

Running the secondPage.html in the web browser gives the following outcome:

window location change path

Setting up the web pages is done. Let’s move to the two different methods for relative URL redirecting.

Method 1: Using the Window Object to Redirect to a Relative URL

In the script file attached to the home.html webpage, create the following function:

Inside this function, use the window object to access its location property, and from that access the href and equal to the path of the secondPage.html. Since it is a relative URL (both the web pages are in the same directory), simply set the href to the name of the second webpage, which is secondPage.html . The function will look like this:

Run the home.html on a web browser and then observe the following functionality:

From the output, it is clear that pressing the button redirects the user to the secondPage.html using its relative URL

Method 2: Using the Document Object to Redirect to a Relative URL

Start by again creating the function created in method 1 with the following lines:

In this function, instead of the window object, this time around using the document object to access the location object. And then, from the location object, access the href property and set it equal to the relative path of the secondPage.html. Since the secondPage is in the same directory, the relative path would only be the name of the second webpage, which is the “secondPage.html”

It is clear that the user was redirected to the second by using the Relative of the second page with the help of JavaScript.

About the author

window location change path

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.

Programming for Data Science with Python

Deciding on a Page Address with Window.location

Javascript is well-known for its ability to modify content on a web page. Less well-known is its ability to move between web pages programmatically so users don’t have to manipulate the browser manually by clicking on links or browser control buttons.

The Javascript standard provides an object called Window.location to handle changing a web page’s address and many other actions. These actions do not directly affect the Document Object Model (DOM) of a particular web page, and may load a new document.

The “location” part of Window.location is its own object type. The Location object is not unique to the Window object that controls the web browser. A single web page can support multiple Location objects.

Window.location is unique because it doesn’t require knowledge of anything on a web page to work. Location objects contain over a dozen properties and methods, and all of these are available to the unique Window.location object.

This article will cover the most commonly used properties and methods of Window.location .

Window.location.href

The window.location.href property returns the URL (Universal Resource Locator) of the current page. Developers can change this property by assigning a new value to it, and the browser will navigate to that new address when the assignment happens.

This example prints out the initial page address, http://example.com , then navigates to the Udacity home page using window.location.href .

Window.location.hostname

The window.location.hostname property returns the domain of a URL. Do not attempt to change this property in code; it will not redirect a web page to another location.

Window.location.pathname

The window.location.pathname property returns the path to the given web page on its server. For a URL that contains a domain but no additional server path, like https://example.com , the property would return an empty string.

The following example returns the path to my author page on the Udacity blog.

Window.location.port

The window.location.port property returns the port through which a web page is served to a user. Web browsers don’t usually show the default port in the address bar for common web protocols, but window.location.port can access them. Sometimes, depending on a server configuration, window.location.port will return an empty string if the default port isn’t shown in the address bar.

The following examples use window.location.port to show the default server ports for http: , https: , and a custom site configuration.

Window.location.protocol

The window.location.protocol property returns the web protocol a web page uses to transfer its information. The most common are http: and https: . These two protocols are similar, but the latter creates a secure connection, while the former does not.

Window.location.assign()

The window.location.assign() method works much like the property window.location.href . It navigates the browser to a new web page. The method has an advantage over the property, though, because the property doesn’t check whether its new URL is valid before trying to navigate.

The window.location.assign() method throws a DOMError if its URL is invalid. This gives developers a chance to catch errors without resorting to complicated URL string matching . Although window.location.href is arguably in more common usage, window.location.assign() is a safer, more robust option.

Window.location is a basic Javascript object that developers commonly rely on to navigate a web browser, but it also has other capabilities that programmers may not immediately be aware of. Changing a page’s address can affect Javascript print and output strategies , as well as raise security concerns.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Window.location and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni

Popular Nanodegrees

Data scientist nanodegree, self-driving car engineer, data analyst nanodegree, android basics nanodegree, intro to programming nanodegree, ai for trading, predictive analytics for business nanodegree, ai for business leaders, data structures & algorithms, school of artificial intelligence, school of cyber security, school of data science, school of business, school of autonomous systems, school of executive leadership, school of programming and development, related articles.

window location change path

Parsing JSON in JavaScript.

window location change path

About JavaScript’s “this” keyword.

window location change path

Closures in JavaScript.

Changing element styling with javascript css.

[et_bloom_locked optin_id=”optin_4″]

Click below to download your preferred Career Guide

Web Developer Career Guide Cloud Career Guide Data Career Guide Robotics Career Guide

[/et_bloom_locked]

IMAGES

  1. Difference between window.location.href, window.location.replace and window.location.assign in

    window location change path

  2. Open a new window with "full path" instead of Search Results\"Path"

    window location change path

  3. What is Windows PATH and How Do You Add to and Edit it?

    window location change path

  4. How to Change Location on Windows 10

    window location change path

  5. How to get the current URL in JavaScript

    window location change path

  6. javascript

    window location change path

VIDEO

  1. Internet Applications: JavaScript (Part3)

  2. Huge World Cup (US vs UK) Crowd in Times Square New York November 25, 2022 #shorts

  3. Shenzhen Airlines A320 Taking off from Chengdu Tianfu International Airport

  4. Should we change...? Path of Titans 7Legends7 Server Update

  5. TIME FOR CHANGE! PATH TO A G MINDSET!

  6. Change Desktop And Other User Folder Locations In Windows 10

COMMENTS

  1. Redirecting to a relative URL in JavaScript

    You can do a relative redirect: window.location.href = '../'; //one level up. or window.location.href = '/path'; //relative to domain.

  2. How to redirect to a relative URL in JavaScript?

    Approach 1: To redirect to a relative URL in JavaScript you can use window.location.href = '/path';. window.location. · Approach 2: To redirect

  3. window.location Cheatsheet

    The window.location object can be used to get information on the current page address (URL). You can also use its method to do a page redirect or refresh...

  4. location.replace()

    The replace() method of the Location interface replaces the current resource with the one at the provided URL. The difference from the

  5. JavaScript Window Location

    The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

  6. How To Redirect to Another Webpage

    ... another webpage with JavaScript. The most popular ones are location.href and location.replace : ... window.location.replace("http://www.w3schools.com");.

  7. How do you redirect to another page in Javascript?

    replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. window.location.href

  8. window.location.href relative paths

    I'm browsing a web app that works fine in Chrome when it does its own changes to window.location but breaks when I do exactly the same commands in Phantom.

  9. How to Redirect to a Relative URL in JavaScript?

    The user can be redirected to another webpage with the help of a relative URL by using either the document.location.href property or the window.location.href

  10. Deciding on a Page Address with Window.location

    The window.location.pathname property returns the path to the given web page on its server. For a URL that contains a domain but no additional