31.使用捕获组进行搜索和替换

说明

搜索本身是有用的。但是,当更改(或替换)你匹配的文本时,你也可以使搜索更加强大。

你可以使用字符串中的.replace()在字符串中搜索和替换文本。.replace()的输入首先是你要搜索的正则表达式模式。第二个参数是替换匹配的字符串或一个执行某件事的函数。

var wrongText = "The sky is silver.";
var silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");
// 返回 "The sky is blue."

你还可以使用美元符号($)访问替换字符串中的捕获组。

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');    
//返回"Camp Code"

练习

编写一个正则表达式以搜索字符串"good"。然后更新replaceText变量,以"okey-dokey"替换"good"。 

  • 你应该使用.replace()进行搜索和替换。
  • 你的正则表达式应该将"This sandwich is good."替换为"This sandwich is okey-dokey."
  • 你不应该改变最后一行。
var huhText = "This sandwich is good.";
var silverRegex = /change/;// Change this line
var replaceText = "";// Change this line
var result = huhText.replace(silverRegex, replaceText);

答案

方法描述
正则表达式正则表达式(英语:Regular Expression,在代码中常简写为regex、regexp或RE)使用单个字符串来描述、匹配一系列符合某个句法规则的字符串搜索模式。
方法描述
replace() 用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

 

var huhText = "This sandwich is good.";
var silverRegex = /good/;// Change this line
var replaceText = "okey-dokey";// Change this line
var result = huhText.replace(silverRegex, replaceText);
result;

运行结果

This sandwich is okey-dokey. 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值