栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在JavaScript中使用类似于PHP的preg_match_all()的正则表达式匹配多个匹配项?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在JavaScript中使用类似于PHP的preg_match_all()的正则表达式匹配多个匹配项?

从评论中悬挂

2020评论:现在,我们不再使用regex,而是

URLSearchParams
为我们完成了所有这些工作,因此不再需要自定义代码,更不用说regex了。


我建议使用另一种正则表达式,使用子组分别捕获参数的名称和值:

function getUrlParams(url) {  var re = /(?:?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,      match, params = {},      depre = function (s) {return depreURIComponent(s.replace(/+/g, " "));};  if (typeof url == "undefined") url = document.location.href;  while (match = re.exec(url)) {    params[depre(match[1])] = depre(match[2]);  }  return params;}var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geopre=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result
是一个对象:

{  f: "q"  geopre: ""  hl: "de"  ie: "UTF8"  iwloc: "addr"  ll: "50.116616,8.680573"  q: "Frankfurt am Main"  sll: "50.106047,8.679886"  source: "s_q"  spn: "0.35972,0.833588"  sspn: "0.370369,0.833588"  z: "11"}

正则表达式分解如下:

(?: # non-capturing group  ?|&         #   "?" or "&"  (?:amp;)?    #   (allow "&", for wrongly HTML-enpred URLs))   # end non-capturing group(   # group 1  [^=&#]+      #   any character except "=", "&" or "#"; at least once)   # end group 1 - this will be the parameter's name(?: # non-capturing group  =?#   an "=", optional  ( #   group 2    [^&#]*     #     any character except "&" or "#"; any number of times  ) #   end group 2 - this will be the parameter's value)   # end non-capturing group


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号