如何从Jquery中的URL获取参数值?

时间:2013-04-12 17:49:58

标签: javascript jquery

大家好我有一个网址,我需要从网址

获取参数
   var URL="http://localhost:17775/Students/199/Kishore"
   //here from the url i need to get the value 199

这是我一直在尝试但这里的值为空

  function getURLParameter(name) { 
    return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]); 
  };

  $(document).ready(function() {
     getURLParameter("Students");
     //i need to get the value 199 from the url
  });

4 个答案:

答案 0 :(得分:2)

虽然可以使用jQuery,但不需要jQuery。有很多方法可以给这只猫上皮。这样的事情应该让你开始朝着正确的方向前进:

var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";

for(var i = 0; i < splitURL.length; i++) {
    if(splitURL[i] == "Students") {
        studentValue = splitURL[i + 1];
        break;
    }
}

这是a working fiddle

修改

根据评论,表明位置将始终相同,提取就像:

var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];

答案 1 :(得分:0)

这是您正在寻找的,因为URL参数将不断变化:

http://jsbin.com/iliyut/2/

var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199

var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234

function getNumber(section) {
  var re = new RegExp(section + "\/(.*)\/","gi");
  var match = re.exec(URL);
  return match[1];
}

答案 2 :(得分:-1)

我会做以下事情:

var url = "http://localhost:17775/Students/199/Kishore"; 
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

答案 3 :(得分:-2)

如果您想要的块总是在同一个地方,这将起作用

var url="http://localhost:17775/Students/199/Kishore"

//break url into parts with regexp
//removed pointless regexp
var url_parts = url.split('/'); 

//access the desired chunk
var yourChunk = url_parts[4]

console.log(yourChunk)