1

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.com/region/town/This-is-the-slug-to-be-matched;art6066,1184999";
var slug = url.match(/[a-z0-9-]/);
orschiro
  • 15,631
  • 18
  • 54
  • 86

4 Answers4

4

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.com/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"
butch
  • 1,992
  • 1
  • 14
  • 21
2

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

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.

Community
  • 1
  • 1
Jeff Noel
  • 6,972
  • 3
  • 35
  • 63
1

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.

Barmar
  • 596,455
  • 48
  • 393
  • 495
1

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

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

Update based on cr0's comment

var slug = url.split('/').pop().split(';')[0];
Atif
  • 9,948
  • 19
  • 60
  • 95
  • I always thought that a slug is used to link to an article in a way you can remember. So I don't get why there are parameters like articleid which is hard to memorize. – cr0 Jul 19 '13 at 19:48