0

I want to add a modified link on a 404 page because I moved the permalink structure from domain.tld/category/title to domain.tld/title. Now when a visitor found an old link to domain.tld/category/title she/he will see the 404 page and there should be a dynamic link to domain.tld/title. This link should be generated if window.location.href contains five "/" (because of http://www.domain.tld/category/title/ has five "/" and my new permalink structure won't have five "/" but only four "/". I know I can replace (remove) the category part with this code:

function geturl(){
 var url = window.location.href;
 alert(url.replace('/category/', '/'));
}

The problem with that is that I have to define a static category name but it could be anything. How to get rid of /category/ part dynamically when there are five "/" in window.location.href?

Peleke
  • 891
  • 2
  • 10
  • 23

3 Answers3

1

Here you go:

function geturl(url){
    if (typeof url === 'string'){
        var a = document.createElement('a');
        a.href = url;
        url = a.pathname;
    }
    else url = window.location.pathname;
    alert(url.replace(/^\/[^\/]+\//, '/'));
}

Call this function using geturl('your url'). If no url is passed, it'll use the page's current url. The regular expression will replace a string at the beginning of the URL's path portion which is inside 2 / characters.

SeinopSys
  • 8,787
  • 10
  • 62
  • 110
  • ... *Where is* the explanation? (sorry, assumed "donde esta" was Spanglishy enough to be understood. ;) My bad!) – Casey Falk Aug 07 '14 at 20:15
  • Wasn't me, but it may be because you have a `^` at the start (which won't match any `window.location.href`. – Casey Falk Aug 07 '14 at 20:17
  • Took back my downvote because this now works, but I still don't think it fully answers the question because there is no conditional for how many segments the url contains. – CoderDennis Aug 07 '14 at 20:25
  • I just realized the OP meant 4 and 5 as the count of slashes total in the URL – SeinopSys Aug 07 '14 at 20:28
0

Preface: this really should be handled by the web server (not your web page), as Mike mentioned.


RegExPal seems to agree with this:

var url = "http://www.domain.tld/category/title/";

url.replace(/\/[^/.]+?\//, "");

Note: not including a "g" in the RegExp will only allow the first instance to be replaced.


That being said, you don't need RegEx. You could just split and then join the URL:

var parts = x.split("/");
parts.splice(3,1);
window.location.href = parts.join("/");
Community
  • 1
  • 1
Casey Falk
  • 2,617
  • 1
  • 18
  • 29
0

it will remove category from url

 function geturl(){
     var url = window.location.pathname; // get url from browser
    // var url = 'http://www.domain.tld/category/title/'; // get url from browser
     var url_array = url.split('/category/');
     var newurl = url_array[0]+"/"+url_array[1];
     alert(newurl);
    }
Noman
  • 4,088
  • 1
  • 21
  • 36