skip to Main Content

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


  1. 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.

    <!DOCTYPE html>
    <html lang="us">
    <head>
        <style>
            textarea#input {
                width: 100%;
                border: 2px solid black;
            }
        </style>
    </head>
    <body>
        <textarea id="input" onkeyup="onChange()" placeholder="your place holder..."></textarea>
        <script>
            const stringCapitalize = (str) => {
                return str.replace(/(^w)|(. w)/g, match => match.toUpperCase());
            }
    
            const onChange = (evt) => {
                const input = document.getElementById("input");
                input.value = stringCapitalize(input.value);
            }
        </script>
    </body>
    </html>
    

    this will now capitalize your first letter of every sentence without capitalizing each word.

    Login or Signup to reply.
  2. 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.

    <textarea id="input" oninput="this.value = this.value.replace(/(^w)|(. w)/g, text => text.toUpperCase())" placeholder=
    "Write something..."></textarea>

    I’m just adding this answer just in case you need it, but it credited to @solitude.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search