Convert string to sentence case in javascript

前端 未结 10 634
别那么骄傲
别那么骄傲 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: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"))

提交回复
热议问题