在javascript中将字符串转换为句子大小写

时间:2013-09-30 08:17:33

标签: javascript jquery

我希望输入的字符串无论如何都应转换为句子。

  

大家好,这是derp。谢谢大家回答我的问题。

转换为

  

大家好,这是derp。谢谢大家回答我的问题。

10 个答案:

答案 0 :(得分:14)

我提出了这种RegExp:

var rg = /(^\w{1}|\.\s*\w{1})/gi;
var myString = "hi all, this is derp. thank you all to answer my query.";
myString = myString.replace(rg, function(toReplace) {
    return toReplace.toUpperCase();
});

答案 1 :(得分:6)

试试这个,它会对你有用。它也适用于具有前导空格的字符串

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);

答案 2 :(得分:0)

尝试演示

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);
}

请注意,所有点并不总是代表行尾,可能是缩写等。此外,它还不确定是否在完全停止后键入空格。这些条件使这个脚本容易受到攻击。

答案 3 :(得分:0)

你也可以尝试这个

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

答案 4 :(得分:0)

这是我最终使用的解决方案:

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;

答案 5 :(得分:0)

以下代码按预期为我工作。

   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;
 }

答案 6 :(得分:0)

我编写了一个基于FSM的函数来合并多个空白字符并将字符串转换为句子大小写。它应该很快,因为它不使用复杂的正则表达式或split并假设您的JavaScript运行时具有高效的字符串连接,那么这应该是最快的方法。它还可以让您轻松添加特殊情况例外。

通过将空白正则表达式替换为比较字符代码的函数,可以进一步提高性能。

function toSentenceCase(str) {

    var states = {
        EndOfSentence  : 0,
        EndOfSentenceWS: 1, // in whitespace immediately after end-of-sentence
        Whitespace     : 2,
        Word           : 3
    };

    var state = states.EndOfSentence;
    var start = 0;
    var end   = 0;

    var output = "";
    var word = "";

    function specialCaseWords(word) {
        if( word == "i" ) return "I";
        if( word == "assy" ) return "assembly";
        if( word == "Assy" ) return "Assembly";
        return word;
    }

    for(var i = 0; i < str.length; i++) {

        var c = str.charAt(i);

        switch( state ) {
            case states.EndOfSentence:

                if( /\s/.test( c ) ) { // if char is whitespace

                    output += " "; // append a single space character
                    state = states.EndOfSentenceWS;
                }
                else {
                    word += c.toLocaleUpperCase();
                    state = states.Word;
                }

                break;

            case states.EndOfSentenceWS:

                if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace

                    word += c.toLocaleUpperCase();
                    state = states.Word;
                }

                break;
            case states.Whitespace:

                if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace

                    output += " "; // add a single whitespace character at the end of the current whitespace region only if there is non-whitespace text after.
                    word += c.toLocaleLowerCase();
                    state = states.Word;
                }

                break;

            case states.Word:

                if( c == "." ) {

                    word = specialCaseWords( word );
                    output += word;
                    output += c;
                    word = "";
                    state = states.EndOfSentence;

                } else if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace

                    // TODO: See if `c` is punctuation, and if so, call specialCaseWords(word) and then add the puncutation

                    word += c.toLocaleLowerCase();
                }
                else {
                    // char IS whitespace (e.g. at-end-of-word):

                    // look at the word we just reconstituted and see if it needs any special rules
                    word = specialCaseWords( word );
                    output += word;
                    word = "";

                    state = states.Whitespace;
                }

                break;
        }//switch
    }//for

    output += word;

    return output;
}

答案 7 :(得分:0)

在每一行上,此脚本将打印.....周日周一周二周三周四周四周五。

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();
}))

答案 8 :(得分:0)

这是我对此post的修改,用于更改为标题大小写。

  

您可以立即toLowerCase字符串,然后toUpperCase每个单词的第一个字母。变成一个非常简单的1班轮:

而不是每个单词都讲。该示例与多行和多行字符串兼容,例如A.M.P.M.,当然,任何单词都以句点和空格字符开头。

您可以在toLowerCaseNames函数下方添加自己的自定义单词,并在下面的示例中添加toUpperCaseNames

// 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))));


您可以将上述所有正则表达式粘贴到https://regexr.com/中,以分解其工作方式。

答案 9 :(得分:0)

以下SentenceCase代码对我来说效果很好,并且还可以处理诸如上午等等。可能需要改进。

//=============================
// SentenceCase Function
// Copes with abbreviations
// Mohsen Alyafei (12-05-2017)
//=============================

function stringSentenceCase(str) {
  return str.replace(/\.\s+([a-z])[^\.]|^(\s*[a-z])[^\.]/g, s => s.replace(/([a-z])/,s => s.toUpperCase()))
}
//=============================

console.log(stringSentenceCase(" start sentence.   second sentence . e.g. a.m. p.m."))
console.log(stringSentenceCase("first sentence. second sentence."))
console.log(stringSentenceCase("e.g. a.m. p.m. P.M. another sentence"))