Using JavaScript to redirect URLs with dynamic path segments

I need help with JavaScript URL redirection since I can’t modify server configs. Here’s what I’m trying to do:

First scenario: When someone visits mysite.com/folder1/folder2/section/ I want to redirect them to mysite.com/newfolder/section/. The tricky part is that “section” could be any name and there might be additional paths after it.

Second scenario: For URLs like mysite.com/folder1/folder2/section/extra/456/ I want to redirect to just mysite.com/newfolder/section/ (removing everything after the section part).

Basically I need to grab the third path segment and use it in the new URL while ignoring whatever comes before or after. How can I write JavaScript code to handle this kind of dynamic URL manipulation?

// Current URL structure: /old/path/DYNAMIC/possible/extras/
// Target URL structure: /new/DYNAMIC/
var currentPath = window.location.pathname;
// Need logic here to extract and rebuild the URL

Any suggestions on how to parse and reconstruct these URLs properly?

I’ve had good luck using regex for URL parsing - it’s way more flexible if you need to change the matching logic later:

var currentPath = window.location.pathname;
var match = currentPath.match(/^\/folder1\/folder2\/([^\/]+)/);
if (match) {
    var sectionName = match[1];
    window.location.href = '/newfolder/' + sectionName + '/';
}

The regex grabs everything between the slashes after ‘folder2’ until it hits the next slash - that’s your dynamic section name. This works great when URLs have weird structures or you want to be picky about what gets redirected. Just test it with different URL variations to make sure it catches everything you expect.

u could also use the URL constructor - it’s cleaner IMO. Just do let url = new URL(window.location); let parts = url.pathname.split('/'); if(parts[3]) location.href = '/newfolder/' + parts[3] + '/'; Works reliably and way easier to debug than regex.

To achieve the desired URL redirection, you can split the current pathname by slashes and filter out any empty segments. Here’s a straightforward approach:

var pathSegments = window.location.pathname.split('/').filter(Boolean);
if (pathSegments.length >= 3 && pathSegments[0] === 'folder1' && pathSegments[1] === 'folder2') {
    var sectionName = pathSegments[2];
    var newUrl = '/newfolder/' + sectionName + '/';
    window.location.replace(newUrl);
}

Using filter(Boolean) ensures you’re working with clean segments, allowing you to accurately build the new URL using the desired section. The replace() method is better for redirects, preventing users from navigating back to the old URL.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.