Chonchol Mahmud
Chonchol Mahmud

Reputation: 2735

SentenceCase in Javascript

I want to make sentence case with JavaScript.

Input:

hello
world
example

I have tried this so far:

   $('.sentenceCase').click(function(event) {
        var rg = /(^\w{1}|\.\s*\w{1})/gi;
        var textareaInput=$('.textareaInput').val();
        myString = textareaInput.replace(rg, function(toReplace) {
            return toReplace.toUpperCase();
        });

       $('.textareaInput').val(myString);
   });

If I input: my name is hello. i have a pen my output is alright. (Output: My name is hello. I have a pen)

But for the first example, the output of my code is:

Hello
world
example

I want the output to be:

Hello
World
Example

How can I do that? (After any fullstop "." the letter will be capital letter)

Upvotes: 1

Views: 225

Answers (2)

Sabith
Sabith

Reputation: 1656

Try this:

$('.sentenceCase').click(function(event) {
    var rg = /(^\w{1}|\.\s*\w{1}|\n\s*\w{1})/gi;
    var textareaInput=$('.textareaInput').val();
    myString = textareaInput.replace(rg, function(toReplace) {
        return toReplace.toUpperCase();
    });
 $('.textareaInput').val(myString);
 });

In your code, you are checking for fullstop(.), but your text contains the new line character. That is the issue.

In this Regex, it will look for the first character in the beginning as well as after '.' and '\n' in the string.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

You only care if the letter is the first letter in a group, so...

/\b\w/g

Matches the word-character that comes after a word boundary - i.e. the first letter in each word.

Upvotes: 1

Related Questions