1

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)

Chonchol Mahmud
  • 2,717
  • 7
  • 39
  • 72
  • 1
    http://stackoverflow.com/questions/19089442/convert-string-to-sentence-case-in-javascript – vaso123 May 26 '16 at 10:07
  • @Chonchoi - not in answer to the question specifically, but you might find an online regex tester helpful. For example https://regex101.com/ This lets you try different things in real time to get to the result you want and can help you to see what your regex will do – Toby May 26 '16 at 10:11
  • 1
    `/\b\w/g` should work better. – Niet the Dark Absol May 26 '16 at 10:11
  • Need fullstop and new line also.for newline its not working but it is working on fullstop. – Chonchol Mahmud May 26 '16 at 10:12
  • How about you simply split your string on dots followd by a space and on newline `\n`? Then uppercase every item first letter and join. – floribon May 26 '16 at 10:18
  • @NiettheDarkAbsol yes its working cool.Write on answer section with brief i will accepted it. – Chonchol Mahmud May 26 '16 at 10:19

2 Answers2

1

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.

Sabith
  • 1,628
  • 2
  • 20
  • 38
1

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592