Convert string to sentence case in javascript

2020-02-01 05:51发布

I want a string entered should be converted to sentence case in whatever case it is.

Like

hi all, this is derp. thank you all to answer my query.

be converted to

Hi all, this is derp. Thank you all to answer my query.

9条回答
▲ chillily
2楼-- · 2020-02-01 06:25

On each line this script will print ..... Sunday Monday Tuesday Wednesday Thursday Friday Saturday.

let rg = /(^\w{1}|\.\s*\w{1})/gi;

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for(let day of days) {
    console.log(day.replace(rg, function(toReplace) {
    return toReplace.toUpperCase();
}))
查看更多
SAY GOODBYE
3楼-- · 2020-02-01 06:29

Here's my modification of this post which was for changing to Title Case.

You could immediately toLowerCase the string, and then just toUpperCase the first letter of each word. Becomes a very simple 1 liner:

Instead of making it every word. This example is compatible with multiple lines and strings like A.M. and P.M. and of course, any word proceeding a period and a whitespace character.

You could add your own custom words below that toLowerCaseNames function and toUpperCaseNames in that example below.

// Based off this post: https://stackoverflow.com/a/40111894/8262102
var str = '-------------------\nhello world!\n\n2 Line Breaks. What is going on with this string. L.M.A.O.\n\nThee End...\nlower case example 1\nlower case example 2\n-------------------\nwait there\'s more!\n-------------------\nhi all, this is derp. thank you all to answer my query.';
function toTitleCase(str) {
 return str.toLowerCase().replace(/\.\s*([a-z])|^[a-z]/gm, s => s.toUpperCase());
}

// Add your own names here to override to lower case
function toLowerCaseNames(str) {
  return str.replace(/\b(lower case example 1|lower case example 2)\b/gmi, s => s.toLowerCase());
}

// Add your own names here to override to UPPER CASE
function toUpperCaseNames(str) {
  return str.replace(/\b(hello|string)\b/gmi, s => s.toUpperCase());
}

console.log(toLowerCaseNames(toUpperCaseNames(toTitleCase(str))));


You can paste all those regexp above into https://regexr.com/ to break down how they work.

查看更多
乱世女痞
4楼-- · 2020-02-01 06:31

The below code is working for me as expected.

   function toSentenceCase(inputString) {
        inputString = "." + inputString;
   var result = "";
   if (inputString.length == 0) {
       return result;
   }

   var terminalCharacterEncountered = false;
   var terminalCharacters = [".", "?", "!"];
   for (var i = 0; i < inputString.length; i++) {
       var currentChar = inputString.charAt(i);
       if (terminalCharacterEncountered) {
           if (currentChar == ' ') {
               result = result + currentChar;
           } else {
               var currentCharToUpperCase = currentChar.toUpperCase();
               result = result + currentCharToUpperCase;
               terminalCharacterEncountered = false;
           }
       } else {
           var currentCharToLowerCase = currentChar.toLowerCase();
           result = result + currentCharToLowerCase;
       }
       for (var j = 0; j < terminalCharacters.length; j++) {
           if (currentChar == terminalCharacters[j]) {
               terminalCharacterEncountered = true;
               break;
           }
       }
   }
        result = result.substring(1, result.length - 1);
   return result;
 }
查看更多
We Are One
5楼-- · 2020-02-01 06:33

You can also try this

<script>
var name="hi all, this is derp. thank you all to answer my query.";
var n = name.split(".");
var newname="";
for(var i=0;i<n.length;i++)
{
var j=0;
while(j<n[i].length)
{
if(n[i].charAt(j)!= " ")
    {
        n[i] = n[i].replace(n[i].charAt(j),n[i].charAt(j).toUpperCase());
            break;
    }
else
  j++;
}

newname = newname.concat(n[i]+".");
 }
alert(newname);
 </script>
查看更多
混吃等死
6楼-- · 2020-02-01 06:41

Try this, It will work fine for you. It will also work for String having leading spaces.

var string="hi all, this is derp. thank you all to answer my query.";
var n=string.split(".");
var vfinal=""
for(i=0;i<n.length;i++)
{
   var spaceput=""
   var spaceCount=n[i].replace(/^(\s*).*$/,"$1").length;
   n[i]=n[i].replace(/^\s+/,"");
   var newstring=n[i].charAt(n[i]).toUpperCase() + n[i].slice(1);
   for(j=0;j<spaceCount;j++)
   spaceput=spaceput+" ";
   vfinal=vfinal+spaceput+newstring+".";
 }
 vfinal=vfinal.substring(0, vfinal.length - 1);
 alert(vfinal);
查看更多
\"骚年 ilove
7楼-- · 2020-02-01 06:44

Try Demo

http://jsfiddle.net/devmgs/6hrv2/

function sentenceCase(strval){

 var newstrs = strval.split(".");
    var finalstr="";
    //alert(strval);
    for(var i=0;i<newstrs.length;i++)
        finalstr=finalstr+"."+ newstrs[i].substr(0,2).toUpperCase()+newstrs[i].substr(2);
    return finalstr.substr(1);
}

Beware all dot doesn't always represent end of line and may be abbreviations etc. Also its not sure if one types a space after the full stop. These conditions make this script vulnerable.

查看更多
登录 后发表回答