📜  标题案例 javascript (1)

📅  最后修改于: 2023-12-03 14:55:38.242000             🧑  作者: Mango

JavaScript Title Case Converter

Introduction

This JavaScript function takes a string and converts it to Title Case. Title Case is where the first letter of each word is capitalized, except for certain words such as 'the', 'of', and 'and'.

Code
function titleCase(str) {
  // array of words to ignore
  const ignoreWords = ['the', 'of', 'and', 'in', 'to', 'a', 'an'];

  // split the string into an array of words
  let words = str.toLowerCase().split(' ');

  // loop through the words
  for(let i = 0; i < words.length; i++) {
    // capitalize the first letter of each word
    words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
    
    // check if the word should be in lowercase
    if(i > 0 && ignoreWords.includes(words[i])) {
      words[i] = words[i].toLowerCase();
    }
  }
  
  // join the array of words back into a string
  return words.join(' ');
}
Example Usage
console.log(titleCase("the quick brown fox")); // "The Quick Brown Fox"
console.log(titleCase("a clash of kings")); // "A Clash of Kings"
console.log(titleCase("in the heart of the sea")); // "In the Heart of the Sea"
console.log(titleCase("to kill a mockingbird")); // "To Kill a Mockingbird"
Conclusion

This JavaScript function is a useful tool for converting strings to Title Case. By making certain words lowercase, it ensures that the output is grammatically correct.