I’m trying to make it so that when a user is entering text in an input field, their sentences will autocapitalize. Some people are already bad enough with proper grammar and punctualization, so this will help make it slightly easier for me when reviewing form entries.
In this example, every word is capitalizing after a user hits space, which is NOT what I want.
Thanks everyone in advance for your help and input.
<html lang="us">
<textarea id="input" onkeyup="onChange()" placeholder=
"Write something..."></textarea>
</html>
<style>
textarea#input {
width: 100%;
border: 2px solid black;
}
</style>
<script>
console.log('example:')
console.log(
"j. delan pegot".replace(/b/g, l => l.toUpperCase()).replace('. ', '. ')
);
const stringCapitalize = (str) => {
return str.replace(/bw/g, l => l.toUpperCase()).replace('. ', '. ')
}
const onChange = (evt) => {
const input = document.getElementById("input");
input.value = stringCapitalize(input.value);
}
</script>
2
Answers
You can achieve sentence based capitalization by using a regular expression, this is to match the first letter of sentence after the period and a space.
On your
stringCapitalize
function i used regular expression to/(. w)|^w/
this is to match 1st letter of each sentence after a period and a space.
this will now capitalize your first letter of every sentence without capitalizing each word.
In regards with @solitude best answer, This is a short way that you can do so using an inline javascript, You can do it like this.
I’m just adding this answer just in case you need it, but it credited to @solitude.