search

Home  >  Q&A  >  body text

javascript - Find a JS regular pattern (take URL parameters)

?id=001&from=1I used reactthis.props.location.searchI have taken out the main part, I don’t understand regular rules, please give me some advice

天蓬老师天蓬老师2757 days ago465

reply all(8)I'll reply

  • 某草草

    某草草2017-05-18 10:49:04

    var str = "?id=001&from=1";
    JSON.parse("{" + 
                     str.replace("?", "\"")
                        .replace(new RegExp(/(&)/g),'\",\"')
                        .replace(new RegExp(/(=)/g),'\":\"')
                   + "\"}")

    reply
    0
  • 某草草

    某草草2017-05-18 10:49:04

    var reg = /([^?=&]+)=([^?=&]*)/g,
        str = window.location.href,
        tempObj = {};
       
    str.replace(reg,function(str,key,val){
        var k = decodeURIComponent(key),
            v = decodeURIComponent(val);
        tempObj[k] = v || "";
        return str;
    });

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-18 10:49:04

    Shouldn’t there be a query in location? Am I confused? . .

    You can consider the following:

    JSON.parse(
        '{' + 
            locatio.search
                .replace('?', '')
                .replace(/&/g, ',')
                .replace(/(\w+)=?(\w+|)/ig, '"":""') + '}')

    It may appear: "?a=1&b=2&c=", or even "?a=1&b=2&c"

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-18 10:49:04

    "?id=001&from=1".replace('?', '').replace('&', ',').replace(/(w+)=(w+)/g, '$1:$2')

    reply
    0
  • 阿神

    阿神2017-05-18 10:49:04

    var parms = location.search.replace("?","").split("&");
    var json = {};
    for(let i = 0, n = parms.length; i<n; i++ ){
        let t = parms[i].split("=");
        json[ t[0] ] = t[1];
    }
    

    The JSON.parse method above is very convenient, but you need to consider the ie8-compatibility issue. The kind I wrote does not need to consider compatibility, but it is more troublesome

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-18 10:49:04

    function GetRequest() {

            var url = location.search; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }

    reply
    0
  • 迷茫

    迷茫2017-05-18 10:49:04

    (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-18 10:49:04

    function get_param(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"),
        r = window.location.search.substr(1).match(reg);
        if(r!=null)return  decodeURI(r[2]); return null;
    }

    reply
    0
  • Cancelreply