Get part of the url pathname via JavaScript regex

▼魔方 西西 提交于 2019-12-21 21:29:10

问题


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.


回答1:


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]



回答2:


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.




回答3:


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

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




回答4:


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



来源:https://stackoverflow.com/questions/21481096/get-part-of-the-url-pathname-via-javascript-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!