首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使每个句子的首字母大写

如何使每个句子的首字母大写
EN

Stack Overflow用户
提问于 2020-08-09 10:45:01
回答 1查看 68关注 0票数 0

我要每个句子的首字母大写。我的代码只大写第一个字,第一个字符的段落。因此,我想大写第一个单词,第一个字符后的句号和感叹号。

示例(我想要这个)

  1. 你好,我好久没见你了!你好!-你好,我好久没见你了!你好吗!
  2. 你好我有一段时间没见你了。你好吗。--你好,我有一段时间没见你了。你好吗。

JsFiddle

代码:

Html代码:

代码语言:javascript
运行
复制
<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代码

代码语言: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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-09 11:06:59

你可以先试着把句子分开。然后,将它们映射到大写字母,如下所示:

代码语言:javascript
运行
复制
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('.');
}
代码语言:javascript
运行
复制
<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!" />

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63325312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档