【发布时间】:2021-06-20 16:13:38
【问题描述】:
我希望使用 JavaScript 的所有句子的第一个字母都是大写的,就像在每个句号 (.) 之后的第一个字符都是大写一样。
像这样:
这是第一句话。这是第二句话。这是第三句
【问题讨论】:
标签: javascript node.js text formatting
我希望使用 JavaScript 的所有句子的第一个字母都是大写的,就像在每个句号 (.) 之后的第一个字符都是大写一样。
像这样:
这是第一句话。这是第二句话。这是第三句
【问题讨论】:
标签: javascript node.js text formatting
以下代码应该可以很好地工作:
text = text.replace(/(\.\s)([a-z])/g, (_, punctuation, char) => {
return punctuation + char.toUpperCase();
});
正则表达式与两个捕获组一起使用,String.prototype.replace 与替换函数一起使用。
【讨论】:
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
【讨论】:
let mySentences = "this is the first sentence. this is the second sentence. this is the third sentence"
let newSentences = "";
// You can use this simple code
mySentences.split(".").map(elem => newSentences += (elem.trim().charAt(0).toUpperCase() + elem.trim().slice(1, elem.length) + "."))
console.log(newSentences)
【讨论】: