admin管理员组

文章数量:1313925

Can't use htaccess, so have to rely on javascript.

Say the url is example/page1/page2/page3/ and I want to redirect this to example/page4/page3/ how would I do this? (and have this work for anything that has anything as page3 and has any subfolders after that as well). And also that page3 can be anything, so a wildcard would have to be in place for this..

Plus: Say the url is example/page1/page2/page3/page5/183/ and I want to redirect this to example/page4/page3/ how would I do this? (cutting off page5 plus anything on the url after that).

Can't use htaccess, so have to rely on javascript.

Say the url is example/page1/page2/page3/ and I want to redirect this to example/page4/page3/ how would I do this? (and have this work for anything that has anything as page3 and has any subfolders after that as well). And also that page3 can be anything, so a wildcard would have to be in place for this..

Plus: Say the url is example/page1/page2/page3/page5/183/ and I want to redirect this to example/page4/page3/ how would I do this? (cutting off page5 plus anything on the url after that).

Share Improve this question edited Jan 30 at 20:47 Malachi asked Jan 30 at 17:48 MalachiMalachi 9776 gold badges16 silver badges32 bronze badges 2
  • rely on javascript If you mean javascript running in a browser you would need to make the urls valid before using them. If you mean javascript running on the server it should be pretty easy. Please clarify. – James Commented Jan 30 at 17:59
  • @James I meant in a browser. – Malachi Commented Jan 30 at 18:36
Add a comment  | 

2 Answers 2

Reset to default 0

Test the contents of the current URL's pathname; if it startsWith("/page1/page2/page3") then do the redirect:

const currentPath = new URL(window.location.href).pathname;
if (currentPath.startsWith("/page1/page2/page3"))
     window.location.replace("/page4/page3");
var pathArray = window.location.pathname.split('/');
var LvlLoc1 = pathArray[1];
var LvlLoc2 = pathArray[2];
var LvlLoc3 = pathArray[3];
var LvlLoc4 = pathArray[4];

then do if statements to verify if LvlLoc1-4 are anything and then do a location.href="https://example/" + whatever you want it to be. As in my example the url is example/page1/page2/page3/ and I want to redirect this to example/page4/page3/:

location.href = "https://example/" + LvlLoc4 + "/" + LvlLoc3 + "/"

I hope that helps anyone out.

本文标签: Wildcard javascript url redirectStack Overflow