<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
/*************** 加入全局的g表示替换所有符合条件的 ***************/
var str1 = 'php php';
var r1 = /h/g;
var result1 = str1.replace(r1, 'H');
console.log(result1); //结果:pHp pHp
/*************** 带有子表达式的例子 ***************/
var str2 = 'php7 and ES5';
var r2 = /(\d)/g;
var result2 = str2.replace(r2, '$1$1');
console.log(result2); //结果:php77 and ES55
/*************** $` 表示捕获的左侧的内容,$' 表示捕获的右侧的内容 ***************/
//替换abc为a[a-b-c]c
var str3 = 'nba';
var result3 = str3.replace(/(b)/g, "[$`-$1-$']");
console.log(result3); //结果:n[n-b-a]a
/*************** 复杂的替换,可以使用函数 ***************/
//替换aaa bbb ccc为Aaa Bbb Ccc
var str = 'aaa bbb ccc';
//console.log(str.match(/[a-z]+/g)); // [ "aaa", "bbb", "ccc" ]
//形参x表示每次匹配的结果
var result = str.replace(/[a-z]+/g, function(x){
//使用substr()函数从零截取到一,从一截取到最后
return x.substr(0,1).toUpperCase() + x.substr(1);
});
console.log(result); //结果:Aaa Bbb Ccc
</script>
</body>
</html>
转载于:https://www.cnblogs.com/phpisfirst/p/9819128.html