1

Trying to make a function that returns UpperCamelCase if true is passed, and lowerCamelCase if false.

I've got the first bit ok so far, but can't figure out how to ignore the first letter of the string. I've used charAt[0] but that returns only the first character.

I've seen these threads but cannot find out how to do it.

This is my code so far:

function sentenceToCamelCase(str, bool) {
  if (bool) {
    return str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  } else {
    return str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  }
}

I get this error:

AssertionError: expected 'ThisSentence' to deeply equal 'thisSentence'

Very new to JS, could anyone give me a hand? Thank you.

Community
  • 1
  • 1
VisualXZ
  • 213
  • 3
  • 17

2 Answers2

1

If the bool parameter is only supposed to change the first character of the output to either lower or upper case you could use the solution below. If this is not what you are looking for let me know in a comment.

function sentenceToCamelCase(str, bool) {
  let res = str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  if(bool) {
    return res[0].toUpperCase() + res.substr(1);
  }
  else {
    return res[0].toLowerCase() + res.substr(1);
  }
}

console.log(sentenceToCamelCase("this sentence", true));
console.log(sentenceToCamelCase("this sentence", false));
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • Thanks for your help. With your solution, it does not pass my first test, which should return 'ThisSentence' when ("this sentence", true) is passed.The function takes two arguments; the sentence, and a boolean, true if UpperCamelCase is to be returned and false if lowerCamelCase is to be returned – VisualXZ Apr 08 '18 at 16:49
  • 1
    @VisualXZ I have updated the method. Does it now pass your test? – gil.fernandes Apr 08 '18 at 16:56
1

You could just search for the space and one character and replace according to the boolean value.

function sentenceToCamelCase(str, bool) {
    var i = +bool;
    return str.replace(/(^|\s+)(.)/g, (_, __, s) => i++ ? s.toUpperCase(): s);
}

console.log(sentenceToCamelCase('once upon a time', true));
console.log(sentenceToCamelCase('once upon a time', false));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392