代码描述:javascript将url指定参数替换。javascript将url中指定参数替换代码实例
在实际应用中,可能需要替换url中参数的内容,下面就是一段能够实现此功能的代码实例,寄希望能够帮到有类似需求的朋友。 代码实例如下:
<script> function parseURL(url){ var a = document.createElement('a'); a.href = url; return { source: url, protocol: a.protocol.replace(':', ''), host: a.hostname, port: a.port, query: a.search, params: (function () { var ret = {}, seg = a.search.replace(/^\\?/, '').split('&'), len = seg.length, i = 0, s; for (; i < len; i++) { if (!seg[i]) { continue; } s = seg[i].split('='); ret[s[0]] = s[1]; } return ret; })(), file: (a.pathname.match(/\\/([^\\/?#]+)$/i) || [, ''])[1], hash: a.hash.replace('#', ''), path: a.pathname.replace(/^([^\\/])/, '/$1'), relative: (a.href.match(/tps?:\\/\\/[^\\/]+(.+)/) || [, ''])[1], segments: a.pathname.replace(/^\\//, '').split('/') }; } //替换myUrl中的同名参数值 function replaceUrlParams(myUrl, newParams) { for (var x in newParams) { var hasInMyUrlParams = false; for (var y in myUrl.params) { if (x.toLowerCase() == y.toLowerCase()) { myUrl.params[y] = newParams[x]; hasInMyUrlParams = true; break; } } //原来没有的参数则追加 if (!hasInMyUrlParams) { myUrl.params[x] = newParams[x]; } } var _result = myUrl.protocol + "://" + myUrl.host + ":" + myUrl.port + myUrl.path + "?"; for (var p in myUrl.params) { _result += (p + "=" + myUrl.params[p] + "&"); } if (_result.substr(_result.length - 1) == "&") { _result = _result.substr(0, _result.length - 1); } if (myUrl.hash != "") { _result += "#" + myUrl.hash; } return _result; } //辅助输出 function w(str){ console.log(str); } var myURL = parseURL('https://www.51qianduan.com:8080/dir/index.html?id=255&m=hello#top'); w("myUrl.file = " + myURL.file) w("myUrl.hash = " + myURL.hash) w("myUrl.host = " + myURL.host) w("myUrl.query = " + myURL.query) w("myUrl.params = " + myURL.params) w("myUrl.path = " + myURL.path) w("myUrl.segments = " + myURL.segments) w("myUrl.port = " + myURL.port) w("myUrl.protocol = " + myURL.protocol) w("myUrl.source = " + myURL.source) var _newUrl = replaceUrlParams(myURL, { id: 101, m: "World", page: 1,"page":2 }); w("修改后的url:") w(_newUrl); </script>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能