Skip to content

Instantly share code, notes, and snippets.

@wesscoby
Created August 13, 2019 17:13
Show Gist options
  • Select an option

  • Save wesscoby/e7a7a7067a5da1d52b41a071213a93e5 to your computer and use it in GitHub Desktop.

Select an option

Save wesscoby/e7a7a7067a5da1d52b41a071213a93e5 to your computer and use it in GitHub Desktop.

Revisions

  1. wesscoby created this gist Aug 13, 2019.
    50 changes: 50 additions & 0 deletions reformat_sentence.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    //! Challenge

    /**
    * You've just finished writing the last chapter for your novel when a virus suddenly
    * infects your document. It has swapped the i's and e's in ei words and capitalized
    * random letters. In today's challenge, you will write a function which will:
    * a) Remove the spelling errors in 'ei' words. (Examples of 'ei' words: their, caffein, deceive, weight)
    * b) Only capitalize the first letter of each sentence.
    * Make sure the rest of the sentence is in lowercase
    ** Example:
    * 'he haD iEght ShOTs of cAffIene.' ==> 'He had eight shots of caffeine.'
    * Good luck and happy coding~!
    */

    // Long Version
    function reformat_sentence(sentence) {
    // Capitalize first letter of string
    const capitalize_first_letter = (word) => word.replace(/^\w/, firstLetter => firstLetter.toUpperCase());

    // convert sentence to array of words,
    // switch 'ie' to 'ei' in each word,
    // convert each word lowercase
    sentence = sentence.split(' ').map(word => {
    word = word.toLowerCase();
    return word.replace('ie', 'ei')
    })

    // Capitalize the first letter of the first word in the sentence array
    sentence[0] = capitalize_first_letter(sentence[0]);

    // Convert sentence back to string and return
    return sentence.join(' ');
    }


    // Short Version
    const reformatSentence = sentence => sentence
    .split(' ')
    .map(word => word.toLowerCase().replace('ie', 'ei'))
    .join(' ')
    .replace(/^\w/, firstLetter => firstLetter.toUpperCase());

    console.log("Long Version:", reformat_sentence('he haD iEght ShOTs of cAffIene.'))
    console.log("Short Version:", reformatSentence('he haD iEght ShOTs of cAffIene.'))

    // Output
    // Long Version: He had eight shots of caffeine.
    // Short Version: He had eight shots of caffeine.