Search and Replace
1. Requirements
- Performs a find and replace on a sentence with a given argument and returns a new sentence.
- The first parameter is the sentence on which to perform the find and replace.
- The second argument is the word that will be replaced (the word before it is replaced).
- The third parameter is used to replace the second argument (the replaced word).
- Preserves the case of the original word when replaced. For example, if you want to replace the word "book" with the word "dog", you should replace it with "dog".
2. Ideas
- Divide a sentence into an array of words using. Split (")
- Determines whether the word to be replaced is capitalized, and the word to be replaced is also capitalized
- Use. IndexOf () to find the index of the replaced word, use. Splice () to delete the word to be replaced, and then add the word to replace it
- Finally, use. Join () to merge the word array into a sentence
3. Code
function myReplace(str, before, after) {str = str.split(" ");if(before[0]>=‘A‘&&before[0]<=‘Z‘){ after = after.slice(0,1).toUpperCase()+after.slice(1);}var num = str.indexOf(before);str.splice(num,1,after);return str.join(" ");}myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
4. RELATED LINKS
- Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
- Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Search and Replace-freecodecamp algorithm topics