Back to Freecodecamp

Challenge 82: SpOoKy~CaSe

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd64.md

latest1.6 KB
Original Source

--description--

Given a string representing a variable name, convert it to "spooky case" using the following constraints:

  • Replace all underscores (_), and hyphens (-) with a tilde (~).
  • Capitalize the first letter of the string, and every other letter after that. Ignore the tilde character when counting. Make all other letters lowercase.

For example, given hello_world, return HeLlO~wOrLd.

--hints--

spookify("hello_world") should return "HeLlO~wOrLd".

js
assert.equal(spookify("hello_world"), "HeLlO~wOrLd");

spookify("Spooky_Case") should return "SpOoKy~CaSe".

js
assert.equal(spookify("Spooky_Case"), "SpOoKy~CaSe");

spookify("TRICK-or-TREAT") should return "TrIcK~oR~tReAt".

js
assert.equal(spookify("TRICK-or-TREAT"), "TrIcK~oR~tReAt");

spookify("c_a-n_d-y_-b-o_w_l") should return "C~a~N~d~Y~~b~O~w~L".

js
assert.equal(spookify("c_a-n_d-y_-b-o_w_l"), "C~a~N~d~Y~~b~O~w~L");

spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts") should return "ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS".

js
assert.equal(spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts"), "ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS");

--seed--

--seed-contents--

js
function spookify(boo) {

  return boo;
}

--solutions--

js
function spookify(boo) {
  const replaced = boo.replace(/[_-]/g, "~");
  
  let result = "";
  let capitalize = true;

  for (let char of replaced) {
    if (char === "~") {
      result += char;
    } else {
      result += capitalize ? char.toUpperCase() : char.toLowerCase();
      capitalize = !capitalize;
    }
  }

  return result;
}