js的正则表达式的替换

时间:2021-07-30 08:57:47

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
var str='Paul,Paula,paul,Ppaul,Paul';//字符串
var result=str.replace(/\bPaul\b/g,"ringo");//将字符串中的Paul单词替换成ringo
document.write(result);
</script>

或者

<script>
var str='Paul,Paula,paul,Ppaul,Paul';//字符串

var substr=new RegExp(/\bPaul\b/,"g")
var result=str.replace(substr,"ringo");//将字符串中的Paul单词替换成ringo
document.write(result);
</script>
</body>
</html>

运行结果为:ringo,Paula,paul,Ppaul,ringo