Js正则匹配提取url的参数值
http://www.nowcoder.com?key=1&key=
2&key=3&test=4#hehe
如何通过key参数获取它的值为[1,2,3],如何写方法?function getparam(url,’key’){
//todo
}
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<script>
var str = "http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe";
var patt1 = /key=\d/ig; //匹配key=开头,后面匹配一个数字 i表示忽略大小写 g表示尽可能多的匹配
document.write("用正则表达式取值为:" + str.match(patt1));
document.write("<br />")
var arr = str.match(patt1);
var result = [];
console.log(str.match(patt1)) // [key=1,key=2,key=3]
for (var i = 0; i < arr.length; i++) {
result.push(parseInt(arr[i].substr(4, 1)));
}
document.write("最终的结果为:[" + result + "]");
</script>
</body>
</html>