Javascript Interview Question String Convert to Title Case

Introduction

A string is in title case if each word in the string is either

  • capitalised (that is, only the first letter of the word is in upper case) or
  • considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
function titleCase(){
   
}
console.log(titleCase('a clash of KINGS', 'a an the of')); // 'A Clash of Kings
console.log(titleCase('THE WIND IN THE WILLOWS', 'The In')); // 'The Wind in the Willows'
console.log(titleCase('the quick brown fox')); // 'The Quick Brown Fox'


// BEST SOLUTION:
let titleCase = (input, minor) => {
  let minorToLower = (typeof minor !== "undefined") ? minor.toLowerCase().split(' ') : [];

  return input.toLowerCase()
    .split(' ')
    .map((w, i) => {
      if (w != "" && ((minorToLower.indexOf(w) === -1) || i == 0)) {
        w = w.split('');
        w[0] = w[0].toUpperCase();
        w = w.join('');
      }
      return w;
    })
    .join(' ');
}

console.log(titleCase('a clash of KINGS', 'a an the of')); // 'A Clash of Kings
console.log(titleCase('THE WIND IN THE WILLOWS', 'The In')); // 'The Wind in the Willows'
console.log(titleCase('the quick brown fox')); // 'The Quick Brown Fox'



PreviousNext

Related