Tianhe Gao

search-and-replace

  1. [Intermediate Algorithm Scripting: Search and Replace | freeCodeCamp.org](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace)
  2. [freeCodeCamp Challenge Guide: Search and Replace - Guide - The freeCodeCamp Forum](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-search-and-replace/16045)

```js function myReplace(str, before, after) { return str }

myReplace('A quick brown fox jumped over the lazy dog', 'jumped', 'leaped') ```

给定三个参数,第一个是待替换的句子,第二个单词来自第一个句子,第三个单词是替换后的单词。如果第二个单词首字母大写,第三个字母在插入第一个句子时也应该是首字母大写。

我的算法,还没成功

```js function myReplace(str, before, after) { / str.match(before)[0] if (before.match(/^[A-Z]+)) { return str.replace(before, after) } after = after .split('') [before.match([A-Z]+)['index']].toUpperCase() .concat(after.substring(before.match([A-Z]+)['index'] + 1)) return str.replace(before, after) }

console.log( myReplace('A quick brown fox Jumped over the lazy dog', 'jumped', 'leaped'), ) ```

答案

```js function myReplace(str, before, after) { const index = str.indexOf(before) if (str[index] = str[index].toUpperCase()) { after = after.charAt(0).toUpperCase() + after.slice(1) } else { after = after.charAt(0).toLowerCase() + after.slice(1) } return str.replace(before, after) } ```

```js function myReplace(str, before, after) { if (^[A-Z].test(before)) { after = after[0].toUpperCase() + after.slice(1) } else { after = after[0].toLowerCase() + after.slice(1) } return str.replace(before, after) } ```


No notes link to this note