|
//下面的例子用來擷取url的兩個參數,並返回urlRewrite之前的真實Url
var reg=new RegExp("()(\d+),(\d+).aspx","gmi");
var url="1017141,20361055.aspx";
//方式一,最簡單常用的方式
var rep=url.replace(reg,"$1ShowBook.aspx?bookId=$2&chapterId=$3");
alert(rep);
//方式二 ,採用固定參數的回呼函數
var rep2=url.replace(reg,function(m,p1,p2,p3){return p1+"ShowBook.aspx?bookId="+p3+"&chapterId="+p3});
alert(rep2);
//方式三,採用非固定參數的回呼函數
var rep3=url.replace(reg,function(){var args=arguments; return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];});
alert(rep3);
//方法四
//方式四和方法三很類似, 除了返回替換後的字串外,還可以單獨擷取參數
var bookId;
var chapterId;
function capText()
{
var args=arguments;
bookId=args[2];
chapterId=args[3];
return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];
}
var rep4=url.replace(reg,capText);
alert(rep4);
alert(bookId);
alert(chapterId);
//除了使用replace方法擷取正則表示式的分組外,還可以使用test ,exec方法擷取分組,只是手法有所不同而已
var reg2=new RegExp("()(\d+),(\d+).aspx","gmi");
var m=reg2.exec("1017141,20361055.aspx");
var s="";
//擷取所有的分組
for (i = 0; i < m.length; i++) {
s = s + m[i] + "n";
}
alert(s);
bookId=m[2];
chapterId=m[3];
alert(bookId);
alert(chapterId);
//使用test方法擷取分組
var reg3=new RegExp("()(\d+),(\d+).aspx","gmi");
reg3.test("1017141,20361055.aspx");
//擷取三個分組
alert(RegExp.$1);
alert(RegExp.$2);
alert(RegExp.$3);
|