MKO_58
MKO_58

Reputation: 21

Removing last part of URL based on

I need to remove any occurence of a product number that may occur in URLs, using javascript/jquery.

URL looks like this: http://www.mysite.com/section1/section2/section3/section4/01-012-15_1571884

The final part of the url is always formatted with 2 digits followed by -, so I was thinking a regex might do the job? I need everything removing after the last /.

It must also work when the product occurs higher or lower in the hierarchy, i.e.: http://www.mysite.com/section1/section2/01-012-15_1571884

So far I have tried different solutions with location.pathname and splits, but I am stuck on how to handle differences in product hierarchy and handling the arrays.

Upvotes: 2

Views: 6889

Answers (5)

providencemac
providencemac

Reputation: 622

Here is an approach that will properly handle a situation where there is no product ID as you requested. http://jsfiddle.net/84GVe/

var url1 = "http://www.mysite.com/section1/section2/section3/section4/01-012-15_1571884";
var url2 = "http://www.mysite.com/section1/section2/section3/section4";

function removeID(url) {

    //look for a / followed by _, - or 0-9 characters, 
    //and use $ to ensure it is the end of the string
    var reg = /\/[-\d_]+$/;

    if(reg.test(url))
    {
         url = url.substr(0,url.lastIndexOf('/'));   
    }
    return url;
}

console.log( removeID(url1) );
console.log( removeID(url2) );

Upvotes: 0

Mina
Mina

Reputation: 1516

var url = 'http://www.mysite.com/section1/section2/section3/section4/01-012-15_1571884';

parts = url.split('/');
parts.pop();
url = parts.join('/');

http://jsfiddle.net/YXe6L/

Upvotes: 2

DEMO

var x = "http://www.mysite.com/section1/section2/section3/section4/01-012-15_1571884";
console.log(x.substr(0,x.lastIndexOf('/')));

Upvotes: 7

Zathrus Writer
Zathrus Writer

Reputation: 4331

var a = 'http://www.mysite.com/section1/section2/01-012-15_1571884',
result = a.replace(a.match(/(\d{1,2}-\d{1,3}-\d{1,2}_\d+)[^\d]*/g), '');

JSFiddle: http://jsfiddle.net/2TVBk/2/

This is a very nice online regex tester to test your regexes with: http://regexpal.com/

Upvotes: 1

yakiro
yakiro

Reputation: 763

Use lastIndexOf to find the last occurence of "/" and then remove the rest of the path using substring.

Upvotes: 3

Related Questions