Daryle
Daryle

Reputation: 13

How can I capitalize the necessary letters to return properly capitalized sentences? JavaScript

This is what I have. Any suggestions would greatly help. Thanks!:

function fixGrammar(input) {
  for (let i = 0; i < input.length; i++) {
    if(i === 0){
      input = input[i].toUpperCase() + input.slice(1);
    }  if(input[i] === (/\s[i+ ]/g)) {
        let capitalize = input[i].toUpperCase()
    } if(input[i] === '.') {
        let afterPeriod = input[i+2];
        afterPeriod.toUpperCase();
      }
    }
  return input;
  }

console.log(fixGrammar("there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more." ))

Upvotes: 1

Views: 56

Answers (3)

mstephen19
mstephen19

Reputation: 1926

Split on periods with any number of trailing spaces, uppercase the first character of each sentence, then join the array on a period and a space.

const paragraph = `there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more.`;

const capitalizeSentences = (str) => {
    return str
        .split(/\.[\s]+/)
        .map((sentence) => `${sentence[0].toUpperCase()}${sentence.slice(1)}`)
        .join('. ');
};

console.log(capitalizeSentences(paragraph));

Upvotes: 0

trincot
trincot

Reputation: 351278

You cannot compare a letter with a regex using == and hope to find a match. Also that regex /\s[i+ ]/g would look for white space followed by a literal i or literal + or a space.

You can use a regex to spot the letters that need to be capitalized, and replace them with replace:

const fixGrammar = s => s.replace(/(?<=^|\. )\w/g, c => c.toUpperCase());

console.log(fixGrammar("there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more." ));

Upvotes: 2

boop_the_snoot
boop_the_snoot

Reputation: 3257

One liner solutions FTW:

Sol 1:

input.split(". ").map(
  m => 
    m[0].toUpperCase() + m.slice(1) // `m[0]` gets the first character, `m.slice(1)` skips the first character and collects the rest of them together.
 ).join(". ")

Sol 2: Or you may make it more verbose:

input.split(". ").map(
    ([firstChar, ...restChars]) => 
       firstChar.toUpperCase() + restChars.join("") // `restChars` would be an array of characters, so we are joining them to get the original substring
    ).join(". ")

In the first sol, m.slice(1) will return string, but if you were to do the same for array, lets say ["a", "b", "c"].slice(1); it would return a new array ["b", "c"].


PS: input is the variable which has the string value. You may use it inside your fixGrammar function. Solution mentioned here assumes that there would be exactly one space after the dot!

Upvotes: 1

Related Questions