亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js中關(guān)于String對象的replace使用詳解

 更新時(shí)間:2011年05月24日 23:29:35   作者:  
關(guān)于String對象的replace使用詳解,需要的朋友可以參考下。
今天在讀Qwrap的源碼stringH時(shí)里邊有個
復(fù)制代碼 代碼如下:

format: function(s, arg0) {
var args = arguments;
return s.replace(/\{(\d+)\}/ig, function(a, b) {
return args[(b | 0) + 1] || '';
});
}

它的使用方式是:
alert(format("{0} love {1}.",'I','You'))//I love you
format的實(shí)現(xiàn)方式主要是用到了String對象的replace方法:

replace:返回根據(jù)正則表達(dá)式進(jìn)行文字替換后的字符串的復(fù)制。

1.平時(shí)常用到的replace
復(fù)制代碼 代碼如下:

function ReplaceDemo(){
var r, re; // 聲明變量。
var ss = "The man hit the ball with the bat.\n";
ss += "while the fielder caught the ball with the glove.";
re = /The/g; // 創(chuàng)建正則表達(dá)式模式。
r = ss.replace(re, "A"); // 用 "A" 替換 "The"。
return(r); // 返回替換后的字符串。
}
ReplaceDemo(); //A man hit the ball with the bat. while the fielder caught the ball with the glove.

2.替換模式中的子表達(dá)式
復(fù)制代碼 代碼如下:

function ReplaceDemo(){
var r, re; // 聲明變量。
var ss = "The rain in Spain falls mainly in the plain.";
re = /(\S+)(\s+)(\S+)/g; // 創(chuàng)建正則表達(dá)式模式。
r = ss.replace(re, "$3$2$1"); // 交換每一對單詞。
return(r); // 返回結(jié)果字符串。
}
document.write(ReplaceDemo()); //rain The Spain in mainly falls the in plain.

匹配正則的項(xiàng):The rain,in Spain,falls mainly,in the;執(zhí)行ss.replace(re, "$3$2$1")操作,完成單詞位置的交換

$1匹配的是第一個(\S+)

$2匹配的是(\s+)

$3匹配的是第二個(\S+)

3.replace第二個參數(shù)是function時(shí)

復(fù)制代碼 代碼如下:

function f2c(s){
var test = /(\d+(\.\d*)?)F\b/g; // 初始化模式。
return(s.replace(test,function($0,$1,$2){return((($1-32)) + "C");}));
}
f2c("Water boils at 212F 3F .2F 2.2F .2");//Water boils at 180C -29C .-30C -29.8C .2

$0匹配 212F,3F,.2F,2.2F
$1匹配 212,3,.2,2.2
$2匹配 最后一個.2

相關(guān)文章

最新評論