Skip to content

Instantly share code, notes, and snippets.

@binary4cat
Last active April 25, 2018 03:23
Show Gist options
  • Save binary4cat/01535cab86d6486281bfaa620c1e9199 to your computer and use it in GitHub Desktop.
Save binary4cat/01535cab86d6486281bfaa620c1e9199 to your computer and use it in GitHub Desktop.
JavaScript从url中获取指定query string的值
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// example
<script src="http://localhost:8080/static/test.js?u=http://localhost:8080/api/get"></script>
var api = "";
var scripts = document.getElementsByTagName("script");
if (scripts && scripts.length > 0) {
for (let i = 0; i < scripts.length; i++) {
if (scripts[i].src.indexOf("ictr") !== -1) {
api = getParameterByName("u", scripts[i].src);
}
}
}
console.log(api) // http://localhost:8080/api/get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment