2.2 KiB
2.2 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7dbb367417b2b2512bab | Use Capture Groups to Search and Replace | 1 | 301368 | 使用捕获组搜索和替换 |
Description
.replace()
方法来搜索并替换字符串中的文本。.replace()
的输入首先是想要搜索的正则表达式匹配模式,第二个参数是用于替换匹配的字符串或用于执行某些操作的函数。
let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");
// Returns "The sky is blue."
你还可以使用美元符号($
)访问替换字符串中的捕获组。
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');
// Returns "Camp Code"
Instructions
"good"
。然后更新变量replaceText
,用字符串"okey-dokey"
替换"good"
。
Tests
tests:
- text: 你应该使用<code>.replace()</code>搜索并替换。
testString: assert(code.match(/\.replace\(.*\)/));
- text: "你的正则表达式应该把<code>'This sandwich is good.'</code>变成<code>'This sandwich is okey-dokey.'</code>。"
testString: assert(result == "This sandwich is okey-dokey." && replaceText === "okey-dokey");
- text: 你不应该改变最后一行。
testString: assert(code.match(/result\s*=\s*huhText\.replace\(.*?\)/));
Challenge Seed
let huhText = "This sandwich is good.";
let fixRegex = /change/; // Change this line
let replaceText = ""; // Change this line
let result = huhText.replace(fixRegex, replaceText);
Solution
let huhText = "This sandwich is good.";
let fixRegex = /good/g; // Change this line
let replaceText = "okey-dokey"; // Change this line
let result = huhText.replace(fixRegex, replaceText);