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
4 Answers
Reset to default 5If 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];