replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
使用
1 | stringObject.replace(regexp/substr,newSubstr/function) |
newSubstr 中如果有 $ 字符具有特定的含义。如下所示,它说明从模式匹配得到的字符串将用于替换1
2
3
4
5$1、$2、...、$99 # 与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。
$& # 与 regexp 相匹配的子串。
$` # 位于匹配子串左侧的文本。
$' # 位于匹配子串右侧的文本。
$$ # 直接量符号。'`
例子
替换第一个1
2var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
1 | Visit W3School! |
全局替换1
2
3
4
5var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
1 | Welcome to W3School! We are proud to announce that W3School |
全局替换1
2
3
4
5var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
1 | Welcome to W3School! We are proud to announce that W3School |
首字母转大写1
2
3
4
5
6
7name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);
}
);
document.write(uw);
1 | Aaa Bbb Ccc |