Peter
Peter

Reputation: 1

How to redirect url based on only one part of the path?

Let me explain what I mean:

I want to redirect from https://example.net/category/83745/my-first-post to https://myredirect.net/my-first-post but without considering /category/numbers/

For the moment I work with this:

if(window.location.pathname == '/category/83745/my-first-post')
{
    window.location.href="https://myredirect.net/my-first-post";
}

And it is working fine but as I described I need to remove /category/numbers/ because they could be different and only consider this part /my-first-post for the redirection.

Thanks in advance.

Upvotes: 0

Views: 663

Answers (4)

user3123035
user3123035

Reputation:

You can run a regular expression match on the pathname

if(window.location.pathname.match(/my-first-post$/)) {
    window.location.href='/my-first-post';
}

More on regexes: https://www.regular-expressions.info/

Another good tool for building and testing regexes: https://regex101.com/

Edit:

To give an example of how to regex according to the more fleshed out specs from Chris G

let pathmatch = window.location.pathname.match(/([^\/]+)$/g);
window.location.href = '/' + pathmatch[0];

Thus, regex can be utilized to grab any pattern and use it later. IF there is a need to make sure the pathname contains category and/or numbers, it is easily added in to the pattern. This one simply disregards anything before the last forward slash (/)

Upvotes: 0

hindmost
hindmost

Reputation: 7195

You can use String's methods lastIndexOf and slice:

var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);

Upvotes: 0

Alex
Alex

Reputation: 1668

if you want to just ignore the first 2 parts dynamically and only care about the last part of the URL then just do the following:

var stringContains = function (str, partial){
    return (str.indexOf(partial) > -1);
};

var url = '/category/83745/my-first-post';


if(stringContains(url, "/category")){
   var parts = a.split("/");
   window.location.href = parts[parts.length-1];
}

Upvotes: 1

Vasyl Moskalov
Vasyl Moskalov

Reputation: 4650

Use Regex. Something like

if(window.location.pathname.match(/\/category\/\d+\/my\-first\-post$/)
{
    window.location.href="https://myredirect.net/my-first-post";
}

Upvotes: 0

Related Questions