如何从.js文件的url获取变量?

Example: Suppose the current page url(window.location.href) is http://example.com/page.html The html page source code is...

<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>

Now I need to use 'src' variables in script.js And the script file script.js should return

var a="Ankit"
var b="18"

Can we use something like echo $_GET like in php?

Found this here. If you're using jQuery, this should be helpful.

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with

var a = getURLParameter("user");
var b = getURLParameter("ptid");

EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.

Maybe outdated but a nice piece of code and would exactly do what was asked for in OP

// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
  // Find all script tags
  var scripts = document.getElementsByTagName("script");

  // Look through them trying to find ourselves
  for(var i=0; i<scripts.length; i++) {
    if(scripts[i].src.indexOf("/" + script_name) > -1) {
      // Get an array of key=value strings of params
      var pa = scripts[i].src.split("?").pop().split("&");

      // Split each key=value into array, the construct js object
      var p = {};
      for(var j=0; j<pa.length; j++) {
        var kv = pa[j].split("=");
        p[kv[0]] = kv[1];
      }
      return p;
    }
  }

  // No scripts match
  return {};
}

Source: James Smith - Extract GET Params from a JavaScript Script Tag