解析url的方法(五种)

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>解析url的方法title>
head>
<body>

body>
html>
<script type="text/javascript">
    /*
    //捕获出var str="zhufeng2016peixun:js+css+HTML5"中的“js+css+HTML5”
    var str="zhufeng2016peixun:js+css+HTML5&node+vue+react";
    var reg=/:([0-9a-zA-Z+]+)/;
    console.log(reg.exec(str)[1]);//"js+css+HTML5"

    var str="zhufeng2016peixun:js+css+HTML5&node+vue+react";
    //"js+css+HTML5"
    //"node+vue+react"
    var reg=/(?::|&)([0-9a-zA-Z+]+)/g;
    console.log(reg.exec(str)[1]);
    console.log(reg.exec(str)[1]);


    var str="zhufeng2016zhufeng:js+css+HTML5";
    var reg=/\w+(\d+)/g;
    var r=reg.exec(str);
    var a=[];
    while(r){
        a.push(r[1]);
        r=reg.exec(str);
    }
    console.log(a);
    //a 为多少?
    */
script>
<script>
    //找出 var url = "www.yyn1109.cn ?course1=js&course2=css&course3=jQ";
    //变成Object {course1: "js", course2: "css", course3: "jQ"}  用正则
    var url = "www.mq1117.cn?course1=js&course2=css&course3=jQ";

    //第一种方案
    function urlToObj(url) {
        url = url.split("?")[1];
        //"course1=js&course2=css&course3=jQ"
        var ary = url.split("&");
        //["course1=js","course2=css","course3=jQ"];
        var obj = {};
        ary.forEach((item) => {
            var a = item.split("=");//["course1","js"]
            obj[a[0]] = a[1];
        });
        return obj;
    }

    //console.log(urlToObj(url));
    //第二种方案
    function urlToObj(url) {
        //按照?,&,=一次性拆分为数组
        var ary = url.split(/[?&=]/);
        //www.mq1117.cn没有用,所以 删除第一项
        ary.shift();
        var obj = {};
        //["course1","js","course2","css","course3","jQ"]
        for (var i = 0; i < ary.length; i += 2) {
            //i   索引 0,2,4
            //i+1 索引 1,3,5
            obj[ary[i]] = ary[i + 1];
        }
        return obj;
    }

    //console.log(urlToObj(url));
    //第三种方案
    function urlToObj(url) {
        url = url.split("?")[1];
        //"course1 =js &course2 =css& course3= jQ"
        //"{course1:'js',course2:'css',course3:'jQ'}"
        //{   =-->:'  & --> ',  '}
        return eval("({" + url.replace(/=/g, ":'").replace(/&/g, "',") + "'})");
    }

    //console.log(urlToObj(url));


    function urlToObj(url) {
        var reg=/[?&](\w+)=(\w+)/g;
        var obj={};
        url.replace(reg,function () {
            obj[arguments[1]]=arguments[2]
        });
        return obj
    }

    function urlToObj(url) {
        url=url.split("?")[1];
        //"course1=js&course2=css&course3=jQ"
        var reg=/(?:^|&)(\w+)=(\w+)/g;
        var reg=/&?(\w+)=(\w+)/g;
        return eval("({"+url.replace(reg,"$1:'$2',")+"})")
    }


    console.log(urlToObj(url));

script>

你可能感兴趣的:(js方法总结)