Skip to content
Advertisement

[‘a’, ‘m’, ‘r’, ‘i’, ‘t’, ‘ ‘, ‘s’, ‘h’, ‘a’, ‘h’, ‘i’], After each ‘ ‘ in a word, would like to display the word. unable to display second word shahi

Would like to to display the word shahi as able to display first-word amrit after ”, is there any way to display last word using code. help appricated.

function cap(cht){
         var part1 = [];
         var data = cht.split("")  //['a', 'm', 'r', 'i', 't', ' ', 's', 'h', 'a', 'h', 'i']
         for (var i = 0; i<data.length; i++){
            if(data[i] === ' '){
                break;
            }
            part1.push(data[i]);
         }
         console.log(part1)
     }
     document.write(cap('amrit shahi'));

Output: [‘a’, ‘m’, ‘r’, ‘i’, ‘t’]

likewise i would like to display shahi if i console log.

Advertisement

Answer

You should have two control structures:

  1. The result array
  2. A buffer to store sub-words

If you run into a space (and the buffer is not empty), add the buffer word to the results and clear it. Anything else is added to the buffer. If you reach the end and the buffer is not empty, add it to the results.

Note: There is no need to call split on the string. Characters can be accessed via str[index] or str.charAt(index).

Edit: Added capitalization

const capitalizeWord = (buffer) =>
  buffer[0].toUpperCase() + buffer.slice(1).join('');

const toTitleCase = (phrase) => {
  const results = [], buffer = [];
  for (let i = 0; i < phrase.length; i++) {
    if (phrase[i] === ' ') {
      if (buffer.length) {
        results.push(capitalizeWord(buffer));
        buffer.splice(0, buffer.length);
      }
    } else {
      buffer.push(phrase[i]);
    }
  }
  if (buffer.length) {
    results.push(capitalizeWord(buffer));
  }
  return results.join(' ');
};

console.log(toTitleCase('amrit shahi'));

This can be rewritten as a switch for better understanding:

const CHAR_SPACE = ' ';

const capitalizeWord = (buffer) =>
  buffer[0].toUpperCase() + buffer.slice(1).join('');
  
const toTitleCase = (phrase) => {
  const results = [], buffer = [];
  for (let i = 0; i < phrase.length; i++) {
    switch (phrase[i]) {
      case CHAR_SPACE:
        if (buffer.length) {
          results.push(capitalizeWord(buffer));
          buffer.splice(0, buffer.length);
        }
        break;
      default:
        buffer.push(phrase[i]);
    }
  }
  if (buffer.length) {
    results.push(capitalizeWord(buffer));
  }
  return results.join(' ');
};

console.log(toTitleCase('amrit shahi'));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement