Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting to a relative URL in JavaScript

I have a problem: I want to redirect via JavaScript to a directory above. My code:

location.href = (location.href).substr(0, (location.href).lastIndexOf('folder')); 

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 could I do that?

like image 897
user199337 Avatar asked Oct 31 '09 17:10

user199337


People also ask

How do I redirect a URL to another URL?

Click the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.

Can you redirect a page to another page using JavaScript How?

It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.

How do you redirect the current page to a new URL say Google com'in JavaScript?

You can use the attr() function of jQuery to redirect a web page as shown below: var url = "http://google.com"; $(location). attr('href',url);

Which of the following is correct syntax to redirect a URL using JavaScript?

Answer: window. location='http://www.newlocation.com';


2 Answers

You can do a relative redirect:

window.location.href = '../'; //one level up 

or

window.location.href = '/path'; //relative to domain 
like image 87
Kobi Avatar answered Oct 09 '22 12:10

Kobi


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.

like image 28
Bob Avatar answered Oct 09 '22 13:10

Bob