I wrote a function to capitalize each letter at the beginning of each sentence. I want to output the text that originally has line breaks to a text-area from a text-area. The output text should preserve these line breaks. But my code is ignoring all the linebreaks. Can you help me with this? My code:
btnPara.addEventListener("click", (e) => {
e.preventDefault();
function paragraphMode(str) {
var splitPara = str
.split(/\r?\n/)
.join(" ")
.split(". ")
.map(
(sentence) => sentence.charAt(0).toUpperCase() + sentence.substring(1)
);
return splitPara.join(". ");
}
outputText.value = paragraphMode(inputText.value);
});
You don't need to process newline, you only need to find all occurrences of first char after a .
. For example, you can use /(^|\.)\s*(\w)/g
const process = s => s.replace(/(^|\.)\s*(\w)/g,w=>w.toUpperCase())
console.log(process("abc. def . g h . ijk lm. \n O \n pq\nR\ns"))
console.log(process("some text is\nwritten here. it doens't\nproperly capitalize sentences.\ncan we fix it?")) // example sentence suggested by @ Scott Sauyet
btw, for the same effect of your origin code (only one space/newline after a period is matched), you simply change \s*
to \r?[\n ]
const input = "abc. def . g h . ijk lm. \n O \n pq\nR"
const result = input.replace(/(^|\.)(\r?\n| )(\w)/g,w=>w.toUpperCase())
console.log(result)