最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - converting URL string into slug - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked May 23, 2013 at 14:47 JCHASE11JCHASE11 3,94119 gold badges71 silver badges133 bronze badges 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
Add a ment  | 

5 Answers 5

Reset to default 5

It is because you are using the wrong slashes

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

Look here:

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

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

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 ponents 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.

Why don't you use

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

which will yield

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

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

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"

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./sonowolise/edit?html,js,console

发布评论

评论列表(0)

  1. 暂无评论