Back to Freecodecamp

Challenge 202: Add Punctuation

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa5.md

latest1.7 KB
Original Source

--description--

Given a string of sentences with missing periods, add a period (".") in the following places:

  • Before each space that comes immediately before an uppercase letter
  • And at the end of the string

Return the resulting string.

--hints--

addPunctuation("Hello world") should return "Hello world."

js
assert.equal(addPunctuation("Hello world"), "Hello world.");

addPunctuation("Hello world It's nice today") should return "Hello world. It's nice today."

js
assert.equal(addPunctuation("Hello world It's nice today"), "Hello world. It's nice today.");

addPunctuation("JavaScript is great Sometimes") should return "JavaScript is great. Sometimes."

js
assert.equal(addPunctuation("JavaScript is great Sometimes"), "JavaScript is great. Sometimes.");

addPunctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z") should return "A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z."

js
assert.equal(addPunctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z"), "A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z.");

addPunctuation("Wait.. For it") should return "Wait... For it."

js
assert.equal(addPunctuation("Wait.. For it"), "Wait... For it.");

--seed--

--seed-contents--

js
function addPunctuation(sentences) {

  return sentences;
}

--solutions--

js
function addPunctuation(sentences) {
  let result = "";

  for (let i = 0; i < sentences.length; i++) {
    if (sentences[i] === " " && i + 1 < sentences.length && /[A-Z]/.test(sentences[i + 1])) {
      result += ".";
    }
    result += sentences[i];
  }
  result += ".";

  return result;
}