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
Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务