justDan
justDan

Reputation: 2333

Find all capital words in paragraph and return title case with JavaScript

I recently have been attempting to check over text in a sentence or paragraph to look for uppercase words and make them title case. Example: 123 SOMEWHERE DR would get formatted to 123 Somewhere Dr. I can get this to work great, but one area I'm a little stuck on is when there are special character items, example: TEST-THIS would get formatted to This-Test and O'SHEA would get formatted to O'Shea.

I thought I could maybe use .replace(), but this is not the case. I can log both Test and This and also O and Shea, but I can't seem to get them back to the original string.

The end result should look like such: 123 West Main Street. Lorem ipsum dolor sit amet, Test-This. New line and O'Shea!.

I have seen many post on SO about capitalizing the first letter of a sentence, or capitalize each word, or look for capitalized words, etc, but I haven't found anything quite as specific as this yet. Any help or tips are appreciated. If I can add or answer anything else please let me know and I will update the question accordingly.

const string = "123 WEST MAIN STREET. Lorem ipsum dolor sit amet, TEST-THIS.  New line and O'SHEA!";

function capitalizeIt(chunk) {
  const text = chunk.split(' ');

  const formatString = text.map((item) => {
    const words = item;
    const specialChars = ["'", "_", "-"];
    const specialRegex = new RegExp('[' + specialChars.join('') + ']');
    const specials = words.split(specialRegex);


    if (words === words.toUpperCase()) {    
      let capLetters = words[0] + words.slice(1).toLowerCase();

      // Here is where I am attempting to format capitalized words
      // that use a special character.
      if (specials.length > 1) {
        specials.map((o) => {
          let test = o[0] + o.slice(1).toLowerCase();

          // I can log test and see both 'Test' and 'This'
          // and 'O' and 'Shea', but here is where I am having
          // a hard time getting them formatted correctly.
          // console.log(test);

          capLetters.replace(test);
        });
      }

      return capLetters;
    } else {
     return words;
    }
  });

  // look for 'undefined' and add line break
  for (let i = 0; i < formatString.length; i++) {
    if (formatString[i] === 'undefined') {
      formatString[i] = '\n\n';
    }
  }

  // output finalString to view for testing
  const finalString = formatString.join(' ');
  document.querySelector('p').textContent = finalString;
}

capitalizeIt(string);
<p id='content'></p>

Upvotes: 1

Views: 174

Answers (1)

Jacob
Jacob

Reputation: 78910

An alternative approach is to use word boundary pseudocharacters (\b):

const allCapsWords = /\b[A-Z]{2,}\b/g;
const string = "123 WEST MAIN STREET. Lorem ipsum dolor sit amet, TEST-THIS.  New line and O'SHEA!";
const titleCased = string.replace(
  allCapsWords,
  word => word[0] + word.slice(1).toLowerCase());

// "123 West Main Street. Lorem ipsum dolor sit amet, Test-This.  New line and O'Shea!"

Upvotes: 1

Related Questions