在JavaScript中解析URL [英] Parsing an URL in JavaScript
本文介绍了在JavaScript中解析URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在JavaScript中解析网址。
I need to parse url in JavaScript.
这是我的代码:
var myRe = /\?*([^=]*)=([^&]*)/;
var myArray = myRe.exec("?page=3&Name=Alex");
for(var i=1;i<myArray.length;i++)
{
alert(myArray[i]);
}
不幸的是它仅适用于第一个 name = value
pair。
Unfortunately it only works for first name=value
pair.
我如何纠正我的代码?
推荐答案
exec
返回匹配项,如果未找到匹配项,则返回null。所以你需要保持 exec
,直到它返回null。
exec
returns a match, or null if no match found. So you need to keep exec
ing until it returns null.
var myRe = /\?*([^=]*)=([^&]*)/;
var myArray;
while((myArray = myRe.exec("?page=3&Name=Alex")) !== null)
{
for(var i=1;i<myArray.length;i++)
{
alert(myArray[i]);
}
}
另外,你的正则表达式是错误的,它肯定是需要th g
切换,但我使用此正则表达式工作:
Also, you're regex is wrong, it definately needs th g
switch, but I got it working using this regex:
var regex = /([^=&?]+)=([^&]+)/g;
参见实例: http://jsfiddle.net/GyXHA/
这篇关于在JavaScript中解析URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文