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

regex - Javascript: match slug of a URL - Stack Overflow

programmeradmin0浏览0评论

For a given URL I want to retrieve its slug using Javascript and a regular expression. I tried the following but it only matches h and not This-is-the-slug-to-be-matched.

var url = ";art6066,1184999";
var slug = url.match(/[a-z0-9-]/);

For a given URL I want to retrieve its slug using Javascript and a regular expression. I tried the following but it only matches h and not This-is-the-slug-to-be-matched.

var url = "http://www.domain./region/town/This-is-the-slug-to-be-matched;art6066,1184999";
var slug = url.match(/[a-z0-9-]/);
Share Improve this question asked Jul 19, 2013 at 19:36 orschiroorschiro 21.9k22 gold badges70 silver badges96 bronze badges 3
  • 2 What part of a URL is its "slug"? – Gabe Commented Jul 19, 2013 at 19:38
  • 1 @Gabe etymology of "slug" – butch Commented Jul 19, 2013 at 19:53
  • I always read about "slug" as the readable part of a URL precisely describing the website's title. – orschiro Commented Jul 19, 2013 at 19:53
Add a ment  | 

4 Answers 4

Reset to default 5

If we can assume the slug always follows the last forward slash and precedes the first colon after the last forward slash:

> var url = "http://www.domain./region/town/This-is-the-slug-to-be-matched;art6066,1184999";
> var slug = url.split("/").pop().split(";")[0];

Output:

> console.log(slug);
  "This-is-the-slug-to-be-matched"

This gets the value after the last slash ( / ) and before the first semi-ma ( ; ):

var slug = url.substring(url.lastIndexOf('/')+1, url.indexOf(';'));

So in this case, slug == "This-is-the-slug-to-be-matched".


Performance review

Comparing .split.pop() answers and .subtring() with .lastIndexOf() functions, my method is at least 35% faster. Scoring ~4m ops/sec against ~2.6m ops/sec.

If performance is an important matter to you, you might want to consider my answer.

Try this:

var slug = url.match(/.*\/([-a-z0-9]+)/i)[1];

.*\/ skips over everything until the last /. [-a-z0-9]+ matches 1 or more alphanumerics or hyphens. Putting the latter in (...) makes it a capture group, and [1] returns the first capture group.

Yet another way (I am assuming you also want ;art6066,1184999 in slug)

var url = "http://www.domain./region/town/This-is-the-slug-to-be-matched;art6066,1184999";   
var slug = url.split('/').pop();

Update based on cr0's ment

var slug = url.split('/').pop().split(';')[0];
发布评论

评论列表(0)

  1. 暂无评论