如何在 Javascript 中使用正则表达式来提取 URL 路径的特定部分 [英] How do I use a regex in Javascript to extract specific parts of a URL path

查看:50
本文介绍了如何在 Javascript 中使用正则表达式来提取 URL 路径的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在尝试采用这种格式的网址:

Right now, I'm trying to take a URL in this format:

https://www.example.com/{section}/posts/{number}

并获取部分和编号.我需要用正则表达式来做;我不能只是把它分成一个部分数组.我试过了:

and get section and number. I need to do it with a regex; I cannot just break it into a parts array. I have tried:

var sect = myURL.match('https://www.example.com/[^/]+');

但我得到作为输出 "https://www.example.com/{section}" 我希望能够获得 section编号.我如何在 Javascript 中执行此操作?

but I get as output "https://www.example.com/{section}" I want to be able to get the section and the number. How do I do this in Javascript?

推荐答案

您可以将 matches 的输出分配给多个变量,如下所示:

You can assign output of matches to multiple variables like this:

var myURL = 'https://www.example.com/mysection/posts/1234';

[$0, sec, num] = myURL.match(/^https?:\/\/www\.example\.com\/([^\/]+)\/posts\/(\d+)\/?$/);

console.log(sec)
//=> mysection

console.log(num)
//=> 1234

正则表达式详情:

  • ^:开始
  • https?:\/\/www\.example\.com\/:
  • ([^\/]+):匹配任何不是 / 的字符的 1+ 并捕获为组 #1
  • \/posts\/:匹配/posts/
  • (\d+):匹配 1+ 位数字并捕获为第 2 组
  • \/?$:在结束前匹配一个可选的尾随/
  • ^: Start
  • https?:\/\/www\.example\.com\/:
  • ([^\/]+): Match 1+ of any character that is not / and capture as group #1
  • \/posts\/: Match /posts/
  • (\d+): Match 1+ digits and capture as group #2
  • \/?$: Match an optional trailing / before end

这篇关于如何在 Javascript 中使用正则表达式来提取 URL 路径的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆