1

I have a function where I am iterating through a given string, alternating the capitalisation of each character and concatenating it to variable alt.

In order to loop through this properly, I have removed spaces from the original string. But I need to add them back at the end of the function.

function alternatingCaps(str) { // 'hello world'
  let words = str.toLowerCase().split(' '); // ['hello','world']
  str       = words.join(''); // 'helloworld'
  let alt = '';
  for(let i = 0; i < str.length; i++) {
    if(i % 2 === 0)
      alt += str[i].toUpperCase();
    else
      alt += str[i].toLowerCase();
  }
  return alt;
} 

console.log(alternatingCaps('hello world'));
/* Output: "HeLlOwOrLd"
   Wanted output: "HeLlO wOrLd" */

Once alt contains a string included as a value in the words array, I want to add a space at the end of the word.

Here was my attempt:

 words.forEach(function(word) {
  if(alt.toLowerCase().includes(word) && word[word.length - 1] === alt[i].toLowerCase())
    alt += ' ';
});

It checks if any of the words in the words array are present in the alt string and if the current character iteration of the string corresponds to the last letter in the word. If so, it adds a space to the string.

But this does not work as intended.

> Output: "HeLlO wOr Ld"
> Wanted output: "HeLlO wOrLd"

I also imagine this would cause problems with duplicate letters. How can I accomplish my goal?

1

2 Answers 2

1

You shouldn't join your words. Keep them as separate elements in the words array then you can loop through that array applying you function to each element.

function alternatingCaps(str) { // 'hello world'
  let words = str.toLowerCase().split(' '); // ['hello','world']

  const alts = words.map(word => capitalizeEvens(word));
  return alts.join(' ');

  function capitalizeEvens(word) {
    let alt = '';
    for(let i = 0; i < word.length; i++) {
      if(i % 2 === 0)
        alt += word[i].toUpperCase();
      else
        alt += word[i].toLowerCase();
    }
    return alt;
  } 

console.log(alternatingCaps('hello world'));
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure this would work considering capitalizeEvens contains a reference to str and not word...
I didn't do this because it causes the alternation to refresh with each word; I want it to be continuous. For example, this code would output HeLlO WoRlD rather than HeLlO wOrLd.
0

You can iterate through your string one char at a time. Then, check whether the characters is an actual word character. If so, alternate the capitalization, if not, add it to the output as it is:

function altCaps(input) {
  var result = '';
  var cap = false;
  for (var i = 0; i < input.length; i++) {
    var c = input[i];
    result += /\w/.test(c) ? (cap = !cap) ? c.toUpperCase() : c.toLowerCase() : c;
  }
  return result;
}

UPDATE: The legible code

function altCaps(input) {
  var result = '';
  var cap = false;
  for (var i = 0; i < input.length; i++) {
    var c = input[i];
    if (/\w/.test(c)) {               // check if char is a "word character" (i.e. letter)
      cap = !cap;                     // toggle next capitalization
      if (cap)                        // if it should capitalize
        result += c.toUpperCase();    // add uppercase letter
      else
        result +=  : c.toLowerCase(); // add lowercase letter
    } else {
      result += c;                    // no letter, so add character as is.
    }
  }
  return result;
}

2 Comments

I am new to Javascript and am having difficulty following the line with multiple ternary operators. Can you explain how that works?
Sure, see my update. Basically, you must think of the ternary operator as a simple inline "if-then-else" construct. The more difficult to understand part was the assignment as part of the condition. In Javascript, even an assignment yields a return value, that evaluates to the assigned value. It can therefore immediately be used inside a condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.