javascript - Convert string to title case with exceptions for articles (a, an, the..etc) - Stack Overflow

I'm creating a small project that will basically convert a string you entered into title case but

I'm creating a small project that will basically convert a string you entered into title case but with the grammatical exceptions of articles (a, an, the, and...etc). So these article exceptions will be lowercase but anything else will be uppercase. I know I need to create an array of these exceptions but don't know how to continue from here. I'm a beginner so I hope something not too plex will achieve this result. Thanks!

const button = document.querySelector('.button');

//event listeners
button.addEventListener('click', grabText);


function grabText() {
  const textBox = document.querySelector('#text-box').value;
  const splitStr = textBox.toLowerCase().split(" ");
  const exceptions = ["and", "the", "a", "an", "for", "to","but", "at","by"]

  for(i = 0; i < splitStr.length; i++) { 
    splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
  }
  const array = splitStr.join(" ");
  array.toString();
  console.log(array);
}

I'm creating a small project that will basically convert a string you entered into title case but with the grammatical exceptions of articles (a, an, the, and...etc). So these article exceptions will be lowercase but anything else will be uppercase. I know I need to create an array of these exceptions but don't know how to continue from here. I'm a beginner so I hope something not too plex will achieve this result. Thanks!

const button = document.querySelector('.button');

//event listeners
button.addEventListener('click', grabText);


function grabText() {
  const textBox = document.querySelector('#text-box').value;
  const splitStr = textBox.toLowerCase().split(" ");
  const exceptions = ["and", "the", "a", "an", "for", "to","but", "at","by"]

  for(i = 0; i < splitStr.length; i++) { 
    splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
  }
  const array = splitStr.join(" ");
  array.toString();
  console.log(array);
}

Share Improve this question asked May 12, 2019 at 18:51 dmking0728dmking0728 5110 bronze badges 4
  • Array.includes() should help you. developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Ringo Commented May 12, 2019 at 18:54
  • 1 Also, consider that the first word of a title should always be capitalized, even if it's a preposition or conjunction. – Ringo Commented May 12, 2019 at 18:55
  • @Ringo oh wow didn't know this even existed. Thanks Ringo!! – dmking0728 Commented May 14, 2019 at 0:26
  • Most programming languages have a method that looks for an item in an array. A good thing to do is to take 10-15 minutes and just read through all the methods available for Array. It can save you a lot of time and energy to know what is built into the language: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Ringo Commented May 14, 2019 at 1:13
Add a ment  | 

5 Answers 5

Reset to default 5

You can use a regular expression replace with callback:

const textBox = document.querySelector('#text-box');;
const output = document.querySelector('#output');

const regex = /(^|\b(?!(and?|at?|the|for|to|but|by)\b))\w+/g;

textBox.addEventListener("input", () =>
    output.textContent = textBox.value.toLowerCase()
          .replace(regex, s => s[0].toUpperCase() + s.slice(1))
);
<textarea id="text-box"></textarea>
<div id="output"></div>

Note that this solution also works when such a exception word is followed by punctuation, e.g. "What for, and what by?" -- "for" and "by" will still be lowercase.

The Array.includes(String) function returns if the string is a part of the array.

This should work,

for(i = 0; i < splitStr.length; i++) { 
    // Check if our word is a part of the exceptions list
    if(i>0 && exceptions.includes(splitStr[i]))
        // if it's an exception skip the capatilization
        continue;

    splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}

Credit for i>0 condition goes to @Ringo, i didn't think about that before. He's right that first word should always be capitalized regardless.

just check if your word is included in exception array or not. I used map function instead of an old hard coding of the for-loop.

function grabText() {
    const textBox = document.querySelector('#text-box').value;
    const splitStr = textBox.toLowerCase().split(" ");
    const exceptions = ["and", "the", "a", "an", "for", "to","but", "at","by"];    
    const result = splitStr.map(word => {
        const formattedWord = exceptions.indexOf(word) == -1 ?
        word.charAt(0).toUpperCase() + word.substring(1) : word;
        // you can also use exceptions.includes(word);
        return formattedWord;
    });
    const array = result.join(" ");
    console.log(array);
}
function sentenceCase (str) {
  if ((str===null) || (str===''))
       return false;
  else
   str = str.toString();

  return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

more information

const convertTitleCase = function (title) {
  const exceptions = ["and", "the", "a", "an", "for", "to", "but", "at", "by"];
  const titleCase = title
    .toLowerCase()
    .split(" ")
    .map(word =>
      exceptions.includes(word) ? word : word[0].toUpperCase() + word.slice(1)
    )
    .join(" ");
  return titleCase[0].toUpperCase() + titleCase.slice(1);;
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745171900a4614976.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信