Milen Mihalev
Milen Mihalev

Reputation: 350

Get part of the url pathname via JavaScript regex

I have following url:

https://www.example.com/article/f/1/test+article

And I need to get "1" part from the url via JavaScript (pure javascript). I know that I can get it with "location.pathname.replace()" but I'm not good with regex.

UPDATE

Just for clarification: "https://www.example.com/article/f/" never changes, it's constant. The only part of the url that can change is "1" (article id) and "test article" (article name). And I want to catch the article id.

Upvotes: 3

Views: 12817

Answers (4)

Jess
Jess

Reputation: 25079

This answer will get only the last /number expression in the url.

Sample data:

https://www.example.com/article/f/1/test+article
http://www.aaa.com/2/thing/1
http://bbb.org/2anotherthing/1?a=b&c=b

The regex:

\/(\d+)\b(?!.*\/(\d+)\b)

  • \/ Look for a slash
  • (\d+) Capture group: get digits of any length
  • \b Word boundary
  • (?!) Negative look ahead. Look ahead to makes sure we do not match the nested regex.
  • .* Any characters.
  • \/(\d+)\b The same regex again, so that we only match the right-most occurrence.

The javascript:

Use javascript exec method to get the captured into an array called cap.

var cap = /\/(\d+)\b(?!.*\/(\d+)\b)/.exec("https://www.example.com/article/f/1/test+article");

Output is the full regex match and the captured group.

["/1", "1", undefined]

Then you can use cap[1] for the first captured group.

Upvotes: 2

gwillie
gwillie

Reputation: 1899

How about split path like:

var path = 'https://www.example.com/article/f/1/test+article';
var pathArray = path.split( '/' );
console.log(pathArray);
console.log(pathArray[5]);

OUTPUT

["https:", "", "www.example.com", "article", "f", "1", "test+article"]
1

I've assumed you know at what 'index' (ie /) the 1 lies at, in your case the 6th (5th from base zero of course) index/element of the array

Upvotes: -1

Vasili Syrakis
Vasili Syrakis

Reputation: 9601

You know you can just match this with \d, right?

Is there some more specific pattern that you need to match?

Upvotes: -1

Silviu Burcea
Silviu Burcea

Reputation: 5348

location.pathname.match(/\/article\/f\/(\d+)/)[1]

I'm trying to match /article/f/ and at least 1 digit captured by the group(note the parenthesis). If that id is the single number in your path, you can get it directly by:

location.pathname.match(/\d+/)[0]

Upvotes: 4

Related Questions