js to get the value of the following parameter in the url path?

1. Specified url

/**
*@param url,name
**/
function getParam(url, name) {
    try {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = url.split('?')[1].match(reg);
        if(r != null) {
          return r[2];
        }
        return "";//如果此处只写return;则返回的是undefined
    } catch(e) {
        return "";//如果此处只写return;则返回的是undefined
    }
};
//调用
//情况一:url包含该参数
var url="http:www.baidu.com?a=111&b=222&c=333";
var name="b";
var re=getParam(url,name);
//输出结果
222
//情况二:url不包含该参数
var url="http:www.baidu.com?a=111&b=222&c=333";
var name="d";
var re=getParam(url,name);
//输出结果
空字符串

2. The url of the current window

  • Get the url parameter value to decode the string encoded by escape().

  • Get the url parameter value to decode the URI encoded by the encodeURI() function.

//对escape()编码的字符串进行解码
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null){
		return unescape(r[2]);
	} 
	return null;//如果此处只写return;则返回的是undefined
};
//对encodeURI()编码过的 URI 进行解码。
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null){
		return decodeURI(r[2]);
	} 
	return "";//如果此处只写return;则返回的是undefined
};

//调用
//情况一:url包含该参数
例如window.location.href="http://192.168.136.104:89/page/test5.html?a=1111&b=2222&c=33333";
var re=getUrlParam("c");
//结果
33333
//情况二:url不包含该参数
例如window.location.href="http://192.168.136.104:89/page/test5.html?a=1111&b=2222&c=33333";
var re=getUrlParam("d");
//结果
空字符串

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325057551&siteId=291194637
Recommended