在字符串中多个大写单词周围添加换行符



编辑,因为不够清楚

我有一些文本从。txt文件,我想在一个HTML页面上显示。我希望在大写行之前和之后都有一个换行符,但不是单独的单词。例如,如果超过2个单词是大写的,它们应该在单独的行上,但如果只有一个单词,则不应该。

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
*/

我该怎么做?

你需要把每个单词分开,把它们分成大写和非大写的两组,然后遍历这些组,检查每个单词,看看每组中是否有多个大写单词。应该像下面这样做:

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
}

最新更新