1

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?

1
  • slug.replace(/\//g, ''); - you're trying to replace backslashes, but you want to remove forward slashes from your example of "/testpress/about/" Commented May 23, 2013 at 14:50

5 Answers 5

5

It is because you are using the wrong slashes

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

Look here:

> "/testpress/about/".replace(/\//g, '')
'testpressabout'
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

Why don't you use

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

which will yield

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

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

Comments

1

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"

2 Comments

The question uses a trailing slash so this will not work. add '\/?' before the '$' to match.
good point! Updated to include this. Also added a group so that the trailing slash will not be returned.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.