【问题标题】:How to Capitalize first word of Every Sentence in JavaScript如何在 JavaScript 中将每个句子的第一个单词大写
【发布时间】:2021-06-20 16:13:38
【问题描述】:

我希望使用 JavaScript 的所有句子的第一个字母都是大写的,就像在每个句号 (.) 之后的第一个字符都是大写一样。

像这样:

这是第一句话。这是第二句话。这是第三句

【问题讨论】:

    标签: javascript node.js text formatting


    【解决方案1】:

    以下代码应该可以很好地工作:

    text = text.replace(/(\.\s)([a-z])/g, (_, punctuation, char) => {
        return punctuation + char.toUpperCase();
    });
    

    正则表达式与两个捕获组一起使用,String.prototype.replace 与替换函数一起使用。

    【讨论】:

      【解决方案2】:

      const txt = "this is the first sentence. this is the second sentence. this is the third sentence";
      const _txt = txt.split('.'); // split the the text into array  by "."
      const _finalText = [];
      for(const tx of _txt) { //loop through the array
          const _tx = tx.trim(); //trim the element since some will contain space.
          const fl = _tx[0].toUpperCase(); //take the first character of the sentence and capitalize it.
          _finalText.push(fl+_tx.substr(1)) //push the result of the concatenation of the first letter(fl) and remaining letters without the first letter into the array;
      }
      console.log(_finalText.join('. ')) // This is the first sentence. This is the second sentence. This is the third sentence

      【讨论】:

      • 那行不通,因为“.”不仅用作句子分隔符——Dr.等,……——而且句子可以被其他字符分隔,比如?!。解析句子是几行代码无法解决的难题。
      • 出现错误。 “未捕获的类型错误:_tx[0] 未定义”
      【解决方案3】:

      let mySentences = "this is the first sentence. this is the second sentence. this is the third sentence"
      
      let newSentences = "";
      
      // You can use this simple code
      mySentences.split(".").map(elem => newSentences += (elem.trim().charAt(0).toUpperCase() + elem.trim().slice(1, elem.length) + "."))
      
      console.log(newSentences)

      【讨论】:

        猜你喜欢
        • 2015-05-30
        • 1970-01-01
        • 2011-07-20
        • 2018-04-24
        • 1970-01-01
        • 2011-01-26
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        相关资源
        最近更新 更多