JCHASE11
JCHASE11

Reputation: 3941

converting URL string into slug

I have a string that looks like this "/testpress/about/" and I need to convert it to "about".

I can easily remove testpress by doing the following:

var slug=relativeUrl.replace("testpress", "");

I have not had luck with removing the slashes:

noslash = slug.replace(/\\/g, '');

How can I go about this so I am left with the desired slug?

Upvotes: 1

Views: 2524

Answers (5)

Dustin
Dustin

Reputation: 376

I like @Michael Coxon's answer but the accepted solution doesn't take into account query parameters or things like '.html'. You could try the following:

getSlugFromUrl = function(url) {
    var urlComponents = url.match(/([^\/]+)/g),
      uri = urlComponents[urlComponents.length - 1];      

    uri = uri.split(/[\.\?\&]/g);
    if (uri.length) {
      slug = uri[0];
    }
    return slug;
  };

This should return only the slug and not anything afterwards.

JSBin here: http://jsbin.com/sonowolise/edit?html,js,console

Upvotes: 0

Michael Coxon
Michael Coxon

Reputation: 5510

I like the RegEx method. That way you can see all the path components.

var path = "/testpress/about/";
var pathComponents = path.match(/([^\/]+)/g);

// to get current page... (last element)
var currentPageSlug = pathComponents[pathComponents.length - 1];

This will work regardless of the trailing slash. The good thing is that no matter how deep the URL structure is, you can always get the path components by referencing them as pathComponents[0], pathComponents[1], pathComponents[2], etc ...

With the RegEx method you also do not need to define 'testpress' in the replace/match/split function. That way it makes your code more reusable.

Upvotes: 3

Ed_
Ed_

Reputation: 19098

You could also use a regular expression to match everything after the slash but before the end of the string, like so:

var text = "testpress/about";
var slug = text.match(/([^\/]+)\/?$/)[1];
//slug -> "about"

Upvotes: 1

fotanus
fotanus

Reputation: 20116

It is because you are using the wrong slashes

noslash = slug.replace(/\//g, '');

Look here:

> "/testpress/about/".replace(/\//g, '')
'testpressabout'

Upvotes: 5

Daniel Pecher
Daniel Pecher

Reputation: 202

Why don't you use

"testpress/about/".split('\/')

which will yield

["testpress", "about", ""]

and there you have it: second element of the array.

Upvotes: 1

Related Questions