Convert string to sentence case in javascript

前端 未结 10 607
别那么骄傲
别那么骄傲 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 19:46

    I came up with this kind of 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();
    });
    
    0 讨论(0)
  • 2020-12-03 19:46

    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>
    
    0 讨论(0)
  • 2020-12-03 19:48

    The following SentenceCase code works fine for me and also handles abbreviations such e.g. a.m. and so on. May require improvements.

    //=============================
    // 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"))

    0 讨论(0)
  • 2020-12-03 19:52

    I wrote an FSM-based function to coalesce multiple whitespace characters and convert a string to sentence-case. It should be fast because it doesn't use complex regular-expression or split and assuming your JavaScript runtime has efficient string concatenation then this should be the fastest way to do it. It also lets you easily add special-case exceptions.

    Performance can probably be improved further by replacing the whitespace regexs with a function to compare char-codes.

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

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

    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.

    0 讨论(0)
提交回复
热议问题