javascript - 如何在 JavaScript 中将每个句子的第一个单词大写
问题描述
我希望使用 JavaScript 的所有句子的第一个字母都是大写的,就像在每个句号 (.) 之后的第一个字符都是大写一样。
像这样:
这是第一句话。这是第二句话。这是第三句话
解决方案
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
推荐阅读
- c# - 当我尝试更改要查看的文件夹时出现“System.NullReferenceException”
- ubuntu - Fail to exporting stata graph and table
- javascript - 计算有多少数组在数组中的第 n 位有值
- amazon-web-services - 查找 ec2 实例 SSH 连接的 AMI 提供程序用户名
- powershell - powershell:将 foreach 循环数据从 csvfile 增加到 xml 输出文件
- javascript - 如何为在类中定义为方法的 fetch 函数编写模拟 fetch 函数?
- python - 如何检查列表的元素是否已被访问
- c - C代码指数计算给出错误的结果
- c# - 对话打开时的方向问题
- google-analytics - 谷歌数据洞察自定义维度显示不正确的数据