JS的replace方法詳細介紹

來源:互聯網
上載者:User

replace() 方法的參數 replacement 可以是函數而不是字串。在這種情況下,每個匹配都調用該函數,它返回的字串將作為替換文本使用。該函數的第一個參數是匹配模式的字串。接下來的參數 是與模式中的子運算式匹配的字串,可以有 0 個或多個這樣的參數。接下來的參數是一個整數,聲明了匹配在 stringObject 中出現的位置。最後一個參數是 stringObject 本身。
下文展示了幾種javascript正則表示式的repalce方式,有些方式我們很少在別的地方看到,如第二種和第三方中方法。
//下面的例子用來擷取url的兩個參數,並返回urlRewrite之前的真實Url
複製代碼 代碼如下:
var reg=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");
var url="http://www.qidian.com/BookReader/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("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");
var m=reg2.exec("http://www.qidian.com/BookReader/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("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");
reg3.test("http://www.qidian.com/BookReader/1017141,20361055.aspx");

//擷取三個分組
複製代碼 代碼如下:
alert(RegExp.$1);
alert(RegExp.$2);
alert(RegExp.$3);

var str="www.baidu.com";
//str.format("好","q")

str.replace(new RegExp("(\\.)(bai)du","g"),function(){

for(var i=0;i<arguments.length;i++)
{
document.write(arguments[i]+"<br/>");
}
document.write("-------------------------------------------------<br/>");
});

兩個例子(證明,replace傳入正則參數和字元傳參數結果不同):
alert("123".replace("1",function(){var un;return un;})); //彈出undefined23
alert("123".replace(new RegExp("1"),function(){var un;return un;})); //彈出23

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.