获取url "?" 后面的字符串

今天写了一个URL “?” 后面的字符串 来改变当前页面的状态

首先需要获取当前页面的URL

 console.log(widow.location) 

之后页面就会打印出来当前的URL

之后我们获取URL后面的字符串

var url =location.search    // 获取url后面的字符串
console.log(url)  //打印url

打印结果:

之后我们需要截取“?””后面的字符串

var str =url.substr(1)  //获取“?”后的字符串
console.log(str)//打印

打印结果:

这样就获取到了“?”后面的字符串

之后需要分割字符串

strs = str.split("&");            
console.log(strs)

打印结果:

所以整体下的代码如下:

console.log(window.location)
            var url = location.search; //获取url中"?"符后的字串
                    console.log(url)
                if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                console.log(str)
                strs = str.split(" ");
                console.log(strs)
                
                
                userId = decodeURIComponent(strs[0].replace("userId=",""));            
//                userName = decodeURIComponent(strs[1].replace("userName=",""));
                
                }
                if(str=="type=1"){
                    $(".toptext").text("11111")
                }else{
                    $(".toptext").text("22222")
                }

其中里面可会会有和我一样刚学前端的同学们会弄不清substr和substring的区别

所以我百度了一下顺便也在这里说一下

substring(from to)    从from位置截取到to-1的位置

eg:此时相当于从from位置截取到原字符串末尾

var a="beautiful"

a.substring(1)  //就是从下标为1的字符(这里是'e')开始起到字符串末尾全部截取,最终获得子串"eautiful"

从from位置截取到to-1的位置

var a ="beautiful"

a.substring(1 5) //相当于从位置为1的字符截取到位置为2的字符,得到子串为:"eaut"

substr(start length)

var a ="beautiful"

a.substr(1 3)// 得到的字符串:“eau”

还有两种特殊情况

当后面的长度超出字符串剩余的长度

var a =“beautiful”

a.substr(3 10)//得到的字符串:“utiful”

另外一种情况是

第一个数字为负数

var a="beautiful"

a.substr(-5 3) //即从倒数第五个字符开始起截取3个长度,获得:"tif"

不带length参数,默认指代从start位置截取到字符串末尾

var a = “beautiful”

a.substr(4)//得到字符串:“tiful”

谢谢大家  这就是我今天要和分享的东西   希望可以帮助到你

2019-04-09

猜你喜欢

转载自www.cnblogs.com/rose-1121/p/10677789.html