Search and Replace-freecodecamp algorithm topics

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.