通过JavaScript正则表达式获取部分URL路径名 [英] Get part of the url pathname via JavaScript regex
问题描述
我有以下网址:
https://www.example.com/article/f/1/test+article
我需要通过JavaScript(纯JavaScript)从网址中获取"1"部分.我知道我可以使用"location.pathname.replace()"来获取它,但是我对正则表达式并不满意.
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.
更新
仅作说明:" https://www.example.com/article/f/"永不改变,它是不变的.网址中唯一可以更改的部分是"1"(商品ID)和测试商品"(商品名称).而且我想抓住商品编号.
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.
推荐答案
location.pathname.match(/\/article\/f\/(\d+)/)[1]
我正在尝试匹配/article/f/和该组捕获的至少1位数字(请注意括号). 如果该ID是您路径中的唯一数字,则可以通过以下方式直接获取它:
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]
这篇关于通过JavaScript正则表达式获取部分URL路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!