Convert string to sentence case in javascript

前端 未结 10 608
别那么骄傲
别那么骄傲 2020-12-03 19:19

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 qu

相关标签:
10条回答
  • 2020-12-03 20:05

    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.

    0 讨论(0)
  • 2020-12-03 20:07

    This is the solution I ended up using:

    str = 'hi all, this is derp. thank you all to answer my query.';
    temp_arr = str.split('.');
    for (i = 0; i < temp_arr.length; i++) {
    temp_arr[i]=temp_arr[i].trim()
    temp_arr[i] = temp_arr[i].charAt(0).toUpperCase() + temp_arr[i].substr(1).toLowerCase();
    }
    str=temp_arr.join('. ') + '.';
    return str;
    
    0 讨论(0)
  • 2020-12-03 20:07

    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;
     }
    
    0 讨论(0)
  • 2020-12-03 20:10

    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);
    
    0 讨论(0)
提交回复
热议问题