javascript - 如何使每个句子的第一个单词第一个字符大写
问题描述
我想要每个句子的第一个单词首字母大写。我的代码只大写第一个单词,第一个字符。所以我想大写第一个单词,句号和感叹号后的第一个字符。
示例(我想要这个):
- 你好,好久没见到你了!你好吗!--> 你好,好久没见到你了!你好吗!
- 你好我有一段时间没见到你了。你好吗。--> 你好,好久没见到你了。你好吗。
代码:
html代码:
<textarea autocomplete="off" cols="30" id="TextInput" name="message" oninput="myFunction()" rows="10" style="width: 100%;"></textarea>
<br><br>
<input id="FistWordFirstCharcterCapital" onclick="FistWordFirstCharcterCapital()" style="color: black;" type="button" value="First word first character capital of each sentence!" />
Javascript代码
<script>
function FistWordFirstCharcterCapital() {
var string = document.getElementById("TextInput").value.toLowerCase();;
var x = string.replace(string[0], string[0].toUpperCase());
document.getElementById("TextInput").value = x;
}
</script>
解决方案
您可以先尝试拆分句子。然后将它们映射为仅首字母大写,如下所示:
function FistWordFirstCharcterCapital() {
var el = document.getElementById("TextInput");
el.value = el.value.split(/[.?!]/).map(str =>{
if(str.charAt(0) == ' ')
return ' ' + str.charAt(1).toUpperCase() + str.slice(2);
else
return str.charAt(0).toUpperCase() + str.slice(1);
}).join('.');
}
<textarea autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;"></textarea>
<br><br>
<input id="FistWordFirstCharcterCapital" onclick="FistWordFirstCharcterCapital()" style="color: black;" type="button" value="First word first character capital of each sentence!" />
推荐阅读
- ignite - Ignite 过期策略不适用于旧数据
- android - .setText 如何从控制器数据类中获取数据
- amazon-web-services - 如何通过 S3 事件或 AWS Lambda 触发 Glue ETL Pyspark 作业?
- javascript - POST 方法后,Chrome 中的 Javascript window.location.href 不起作用
- react-native - 'android/app/build/outputs/apk/debug/app-debug.apk' 中的应用程序不存在或无法访问
- javascript - 为什么我不能将 weekstart 设置为星期一?
- python - 如何将 json 对象数组内的列表中的 dict 转换为数据框?
- ios - IOS swift的谷歌地图中的折线
- python - 如何对由字典组成的列表进行排序?
- php - 将来自远程 url 的动态数据加载到引导模式弹出窗口中