Skip to content
Advertisement

Add line breaks around multiple uppercase words in a string [closed]

Edited because i wasn’t clear enough

I have some text from a .txt file, that i want to display on a HTML page. I want to have a linebreak before- and after an uppercase line, but not for standalone words. Like if more than 2 words are uppercase, they should be on a seperate line, but not if its only one word.

const text1 = "I want THIS ON A SEPERATE LINE but not THIS text here";

function convertText(text) {
...check for uppercase line....
 document.write(modifiedText)
}
convertText(text1);


/*
Wanted result: 

I want 
THIS ON A SEPERATE LINE
but not THIS text here
*/

How can I do this?

Advertisement

Answer

You’ll need to split each word up, put them into groups of capitalised and non-capitalised and then iterate through those groups, checking each word to find if there are multiple capitalised words in each group. Something like the following should do the job:

function convertText(text) {
  const words = text.split(' '); // split the string into an array of word strings
  let currentLine = '';
  // groups of words of the same case
  const wordGroups = [];
  let lastWordWasAllCaps = false;

  // group words by case
  for (const word of words) {
    if (word === word.toUpperCase()) {
      if(!lastWordWasAllCaps) {
        // word is in block capitals, but the last one wasn't
        wordGroups.push(currentLine);
        currentLine = word;
      } else {
        currentLine = currentLine.concat(' ', word);
      }
      lastWordWasAllCaps = true;
    } else {
      if (lastWordWasAllCaps) {
        // word is not in block capitals, but the last one was
        wordGroups.push(currentLine);
        currentLine = word;
      } else {
        currentLine = currentLine.concat(' ', word);
      }
      lastWordWasAllCaps = false;
    }
  }
  // push the last line
  wordGroups.push(currentLine);

  let finalString = '';
  let breakNextLine = true;
  // now look through the groups of words and join any single full capital words to their siblings
  for (const wordGroup of wordGroups) {
    // if a group is all caps and has no spaces, join it without a line break
    if (wordGroup === wordGroup.toUpperCase() && !wordGroup.includes(' ')) {
      finalString = finalString.concat(' ', wordGroup);
      // tell the next set to join without a line break
      breakNextLine = false;
    } else {
      if (breakNextLine) {
        finalString = finalString.concat('n', wordGroup);
      } else {
        finalString = finalString.concat(' ', wordGroup);
      }
      breakNextLine = true;
    }
  }
  return finalString.slice(2); // remove the added spaces at the start
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement