首页 > 解决方案 > 如何使每个句子的第一个单词第一个字符大写

问题描述

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

示例(我想要这个)

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

JsFiddle

代码:

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>

标签: 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('.');
}
<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!" />


推荐阅读