首页 > 解决方案 > 如何在 JavaScript 中将每个句子的第一个单词大写

问题描述

我希望使用 JavaScript 的所有句子的第一个字母都是大写的,就像在每个句号 (.) 之后的第一个字符都是大写一样。

像这样:

这是第一句话。这是第二句话。这是第三句话

标签: javascriptnode.jstextformatting

解决方案


const txt = "this is the first sentence. this is the second sentence. this is the third sentence";
const _txt = txt.split('.'); // split the the text into array  by "."
const _finalText = [];
for(const tx of _txt) { //loop through the array
    const _tx = tx.trim(); //trim the element since some will contain space.
    const fl = _tx[0].toUpperCase(); //take the first character of the sentence and capitalize it.
    _finalText.push(fl+_tx.substr(1)) //push the result of the concatenation of the first letter(fl) and remaining letters without the first letter into the array;
}
console.log(_finalText.join('. ')) // This is the first sentence. This is the second sentence. This is the third sentence


推荐阅读