Home > Backend Development > PHP Tutorial > Regular example sharing for matching url parameters

Regular example sharing for matching url parameters

小云云
Release: 2023-03-20 19:20:02
Original
2408 people have browsed it

本文主要和大家分享匹配url参数的正则实例,希望能帮助到大家。

/([^?&=]+)=([^?&=]*)/g

解释:

前后的斜杠/是正则表达式的分隔符,最后的g表示全局匹配,匹配到第一个之后不会停下来,会继续匹配,相当于PHP里的preg_match_all,没有g就相当于preg_match,下面有例子说明.

()表示子组.

[^]表示字符类取反,比如[^abc]匹配的就是不是a和b和c的单个字符,[^?&=]匹配不是^和?和=的单个字符.

字符类[]后面的+和*表示量词:
+ 等价于 {1,} 重复1次或多次
* 等价于 {0,} 重复0次或多次

var str = "foo=bar&lang=js";var reg = /[^?&=]{1,}=[^?&=]{0,}/g;
console.log(str.match(reg)); //输出 ["foo=bar", "lang=js"]var str = "foo=bar&lang=js";var reg = /[^?&=]{1,}=[^?&=]{0,}/;
console.log(str.match(reg)); //输出 ["foo=bar"]var str = "foo=bar&lang=js";var reg = /([^?&=]{1,})=([^?&=]{0,})/;
console.log(str.match(reg)); //输出 ["foo=bar", "foo", "bar"]//下面是提取参数部分为转为对象的代码
Copy after login
var getQueryObject=function (url) {
    url=url==null?window.location.href:url    var search=url.substring(url.lastIndexOf("?")+1)    var obj={}    //   ^?&= 匹配不是?或&或=的单个字符    var reg=/([^?&=]+)=([^?&=]*)/g    search.replace(reg,function (rs,$1,$2) {        debugger        var name=decodeURIComponent(arguments[1])        var val=decodeURIComponent(arguments[2])        obj[name]=val        return    })    return obj}
Copy after login

相关推荐:
JS正则表达式如何替换url参数

javascript怎么获取URL参数的值?

简单介绍javascript的url参数parse和build函数

The above is the detailed content of Regular example sharing for matching url parameters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template