JavaScript Program to Capitalize the First Letter of Every Sentence in a String
Last Updated :
13 Oct, 2023
In this article, we will see how Capitalizing the first letter of every sentence in a string is a common text manipulation task in JavaScript. It involves identifying sentence boundaries and ensuring that the first letter of each sentence is in uppercase.
Examples:
Input: "this is Geeks for Geeks website. hello there!"
Output: "This is Geeks for Geeks website. Hello there!"
Input: "hello. how are you."
Output: "Hello. How are you."
- Split the text into sentences using a regular expression.
- Capitalize the first letter of each sentence using a combination of toUpperCase() and substring().
Example: Here, is the implementation of the above approach
Javascript
function capitalizeSentences(text) {
const sentences = text.split(/\.|\?|!/);
const capitalizedSentences = sentences
.filter(sentence =>
sentence.trim() !== '' )
.map(sentence =>
sentence.trim()[0]
.toUpperCase() +
sentence.trim().slice(1));
return capitalizedSentences.join( '. ' ) + '.' ;
}
const inputText =
`geeks for geeks for
students.hello students.`;
const result = capitalizeSentences(inputText);
console.log(result);
|
Output
Geeks for geeks for
students. Hello students.
- Split the text into an array of sentences using the split() method with sentence-ending punctuation marks as delimiters.
- Capitalize the first letter of each sentence and join the sentences back together.
Example: Here, is the implementation of the above approach
Javascript
function capitalizeSentences(text) {
const sentences =
text.split(/[.!?]/)
.filter(sentence =>
sentence.trim() !== '' );
for (let i = 0; i < sentences.length; i++) {
sentences[i] =
sentences[i].trim()[0].toUpperCase() +
sentences[i].trim().slice(1);
}
return sentences.join( '. ' ) + '.' ;
}
const inputText = "geeks for geeks. hello students."
const result = capitalizeSentences(inputText);
console.log(result);
|
Output
Geeks for geeks. Hello students.
Share your thoughts in the comments
Please Login to comment...