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

小编典典

从评论中悬挂

2020评论:现在,我们不再使用regex,而是URLSearchParams为我们完成了所有这些工作,因此不再需要自定义代码,更不用说regex了。

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

function getUrlParams(url) {

var re = /(?:\?|&(?:amp;)?)([^=]+)(?:=?([^]*))/g,

match, params = {},

decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

if (typeof url == "undefined") url = document.location.href;

while (match = re.exec(url)) {

params[decode(match[1])] = decode(match[2]);

}

return params;

}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&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"

geocode: ""

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-encoded 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

2020-05-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值