0

I want first word first character capital of each sentence. My code only capitalizing first word, first character of para. So I want to capitalize first word, first character after full stop and exclamation mark.

Example(I want this):

  1. hello I haven't seen you for awhile! how are you! --> Hello I haven't seen you for awhile! How are you!
  2. hello I haven't seen you for awhile. how are you. --> Hello I haven't seen you for awhile. How are you.

JsFiddle:

Code:

Html Code:

<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 code

<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>
santosh
  • 742
  • 8
  • 19
  • const toTitleCase = s => s.substr(0, 1).toUpperCase() + s.substr(1).toLowerCase(); – Sumit Yadav Aug 09 '20 at 10:47
  • This may be helpful https://stackoverflow.com/questions/42755664/capitalize-first-letter-of-each-word-in-js – Nilambar Sharma Aug 09 '20 at 10:51
  • In css write .capitalize { text-transform: capitalize; } In JavaScript, you can add the class to an element document.getElementById("element").className = "capitalize"; – Satish Hawalppagol Aug 09 '20 at 10:58
  • @Satish Hawalppagol I wan first word first character capital of each sentence. I mean whatever word comes after full stop and exclamation mark I want it should be capital – santosh Aug 09 '20 at 11:05

1 Answers1

1

You can try splitting the sentences first. Then map them to uppercase only the first letter like the following way:

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!" />
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thanks, still their is the problem after paragraph changes this not making second paragraph first word, first character capital. – santosh Aug 09 '20 at 11:13