今天在读Qwrap的源码stringH时里边有个
复制代码 代码如下:
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的实现方式主要是用到了String对象的replace方法:

replace:返回根据正则表达式进行文字替换后的字符串的复制。

1.平时常用到的replace
复制代码 代码如下:
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; // 创建正则表达式模式。
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.替换模式中的子表达式
复制代码 代码如下:
function ReplaceDemo(){
var r, re; // 声明变量。
var ss = "The rain in Spain falls mainly in the plain.";
re = /(\S+)(\s+)(\S+)/g; // 创建正则表达式模式。
r = ss.replace(re, "$3$2$1"); // 交换每一对单词。
return(r); // 返回结果字符串。
}
document.write(ReplaceDemo()); //rain The Spain in mainly falls the in plain.

匹配正则的项:The rain,in Spain,falls mainly,in the;执行ss.replace(re, "$3$2$1")操作,完成单词位置的交换

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

$2匹配的是(\s+)

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

3.replace第二个参数是function时

复制代码 代码如下:
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
标签:
String,replace

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“js中关于String对象的replace使用详解”

暂无“js中关于String对象的replace使用详解”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。