replace()方法用于在字符串中用一些字符替换另一些字符,或者换一个与正则表达式匹配的子串
1.语法:
stringObject.replace(regexp/substr,replacement)
参数 | 描述 |
---|---|
regexp/substr | 必需。规定子字符串或要替换的模式的 RegExp 对象。 |
replacement | 一个字符串值。规定了替换文本或生成替换文本的函数 |
2.例子:
<script type="text/javascript">
//替换
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
//console.log:Visit W3School!
</script>
//转大写
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);